[英]Variable (dialogView) is accessed from within inner class, needs to be declared final
I am trying to create an alert dialog with a layout Yes or No. I want to dismiss the dialog by clicking the 'No' button but dialogView.dismiss();
我正在尝试创建一个带有布局“是”或“否”的警告对话框。我想通过单击“否”按钮但是dialogView.dismiss();
来关闭对话框dialogView.dismiss();
has an error. 有错误。
Here is my code. 这是我的代码。
private void showCancelOrderDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.dialog_details_cancel_order, null);
builder.setView(dialogView);
ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.WHITE);
SpannableStringBuilder ssBuilder = new SpannableStringBuilder(db_title);
ssBuilder.setSpan(foregroundColorSpan,0,db_title.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
builder.setTitle(ssBuilder);
yes = dialogView.findViewById(R.id.btn_yes);
yes.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
////////////////////////////
}
});
no = dialogView.findViewById(R.id.btn_no);
no.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialogView.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
Change your definition of dialogView
from this: 从这里更改dialogView
的定义:
View dialogView = inflater.inflate(R.layout.dialog_details_cancel_order, null);
...to this: ......对此:
final View dialogView = inflater.inflate(R.layout.dialog_details_cancel_order, null);
The reason being dialogView
is seen by 2 methods: the one hosting your entire snippet, and onClick
within the anonymous View.OnClickListener
class. 可以通过2种方法看到dialogView
的原因:托管整个代码段的方法,以及匿名View.OnClickListener
类中的onClick
。
If two methods see the same local variable, Java wants you to make it final. 如果两个方法看到相同的局部变量,Java希望您使其成为最终的。 Effectively ruling out the possibility of that field being changed in the future. 有效排除未来该领域发生变化的可能性。
Together with the absence of by-reference parameters, this rule ensures that locals are only assigned in the method that they belong to. 与缺少引用参数一起,此规则确保仅在其所属的方法中分配局部变量。 Code is thus more readable. 因此代码更具可读性。
@Hadi Satrio is right. @Hadi Satrio是对的。 As you have assign instance of View class locally and accessing from listener, you need to declare it as final. 由于您已在本地分配View类的实例并从侦听器进行访问,因此需要将其声明为final。 If you don't want to make it final, you can define it as global variable. 如果您不想将其设为最终,则可以将其定义为全局变量。 If you want more detail use this link. 如果您想要更多细节,请使用此链接。 Variable is accessed within inner class. 变量在内部类中访问。 Needs to be declared final 需要宣布最终
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.