4

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();
}
Supriya
  • 290
  • 4
  • 15
niel
  • 125
  • 9
  • Your answer below containing thanks was deleted. To acknowledge people who helped you, you can upvote them (to thank them for effort or correctness) and for the answer that you found most helpful, you can accept the answer, by clicking the tick mark to the left of that answer. Doing so marks the question as resolved, and gives the helper some additional points for being a valuable member of the community. – halfer Feb 11 '18 at 13:23

2 Answers2

2

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
  • 4,272
  • 2
  • 24
  • 45
1

@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

Vatsal Desai
  • 169
  • 4