この質問は以前に何度か聞かれたことは知っていますが、多くの回答を読んでも、自分に合ったものが見つかりませんでした. まず、次のコードを見てください。これは、画像がクリックされると AlertDialog を開くはずです (これは完全に機能します)。AlertDialog は EditText フィールドをホストします - ここで問題が発生します:
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
。Cannot refer to a non-final variable inside an inner class defined in a different method
これが、画像を 2 回目にクリックしたときにエラーが発生する理由です。
それで、私が望むことを達成できる方法はありますか?
ありがとう!