Access variables (dialogView) from inner classes, need to be declared as final… here is a solution to the problem.
Access variables (dialogView) from inner classes, need to be declared as final
I’m trying to create a warning dialog with a layout of “is” or “no”. I want to close the dialog by clicking the “No” button, but dialogView.dismiss();
An error occurred.
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();
}
Solution
Change the definition of dialogView
from here:
View dialogView = inflater.inflate(R.layout.dialog_details_cancel_order, null);
… To this end:
final View dialogView = inflater.inflate(R.layout.dialog_details_cancel_order, null);
The reason for the dialogView
is seen in 2 ways: the method that hosts the entire code snippet, and the onClick in the
anonymous View.OnClickListener
class
If both methods see the same local variable, Java wants you to make it final. The possibility that the field will be changed in the future is effectively ruled out.
Together with no reference parameters, this rule ensures that local variables are assigned only in the method to which they belong. The code is therefore more readable.