Java – to access a variable (dialogview) from an internal class, you need to declare final

I'm trying to create a warning dialog with layout "yes" or "no". I want to close the dialog by clicking the "no" button, but the dialog box view. Disass(); There is a mistake

This 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();
}

resolvent:

Change the definition of dialogview from here:

View dialogView = inflater.inflate(R.layout.dialog_details_cancel_order, null);

... in this regard:

final View dialogView = inflater.inflate(R.layout.dialog_details_cancel_order, null);

The reason for dialogview can be seen in two ways: the method that hosts the entire code segment, and onclick. In the anonymous view. Onclicklistener class

If the two methods see the same local variable, Java wants you to make it final. Effectively eliminate the possibility of changes in this field in the future

Together with missing reference parameters, this rule ensures that local variables are allocated only in the method to which they belong. Therefore, the code is more readable

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>