Android:无法引用在其他方法中定义的内部类中的非最终变量
我知道这个问题以前已经被问过好几次了,但我在阅读了很多答案后,还没有找到适合我的答案。首先,请看下面的代码,它应该在单击图像后打开AlertDialog(这非常有效)。AlertDialog承载一个EditText字段-这就是问题产生的原因:Android:无法引用在其他方法中定义的内部类中的非最终变量,android,android-edittext,android-alertdialog,final,Android,Android Edittext,Android Alertdialog,Final,我知道这个问题以前已经被问过好几次了,但我在阅读了很多答案后,还没有找到适合我的答案。首先,请看下面的代码,它应该在单击图像后打开AlertDialog(这非常有效)。AlertDialog承载一个EditText字段-这就是问题产生的原因: ImageView scissorsImage = (ImageView) findViewById(R.id.scissorsImage); scissorsImage.setOnClickListener(new View.OnClic
ImageView scissorsImage = (ImageView) findViewById(R.id.scissorsImage);
scissorsImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View view)
{
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Apply a Coupon");
alert.setMessage("Enter the coupon amount (i.e. 25 for $25)");
// Set an EditText view to get user input
final EditText couponAmount = new EditText(context);
alert.setView(couponAmount);
couponAmount.setText(couponAmountString);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String couponAmountString = couponAmount.getText().toString();
System.out.println(couponAmountString);
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
}
});
现在,这段代码位于我的onCreate
方法内部,变量couponAmountString
位于onCreate
方法外部。因此代码执行得很好,唯一的问题是行couponAmount.setText(couponAmountString)代码>无法按我希望的方式工作
我试图用它来做的是,当用户在对话框中输入一个值,然后按OK关闭它时,该值将存储在couponAmountString
-到目前为止还不错。当用户再次触摸图像以重新打开对话框时,我试图用他们输入的最后一个值预先设置EditText字段,因此couponAmount.setText(couponAmountString)代码>。但这不起作用,因为我必须将EditText字段声明为final
。这就是为什么当我第二次单击图像时,错误无法引用在不同方法中定义的内部类中的非最终变量
那么,有什么方法可以实现我想要的吗
谢谢 我真傻,真傻。正如您所看到的,我在方法内部重新初始化了couponAmountString。我只需要拿出字符串
,它现在就可以工作了