简体   繁体   中英

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(); 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:

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.

If two methods see the same local variable, Java wants you to make it final. 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. As you have assign instance of View class locally and accessing from listener, you need to declare it as 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM