0

我知道这个问题之前已经被问过好几次了,但是在阅读了很多答案后,我还没有找到适合我的东西。首先,请看下面的代码,它应该在单击图像后打开一个 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方法内,而变量couponAmountStringonCreate方法外。所以代码执行得很好,唯一的问题是该行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第二次单击图像时出现错误的原因。

那么有什么方法可以完成我想要的吗?

谢谢!

4

1 回答 1

1

傻,傻我。事实证明,如您所见,我在方法内重新初始化了 couponAmountString。我只需要拿出来String,它现在正在工作!

于 2012-08-17T02:38:07.343 回答