I want to Show an Alert Dialog Box in android on onBackPressed() event
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
//@Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
break;
case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
break;
}
}
};
But I am getting error when executing it in onBackPressed() event
@Override
public void onBackPressed() {
super.onBackPressed();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure?").setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();
}
Error : "com.java.mypkg has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@406c3798 that was originally added here"
Do I have missed something. Pls help.
Yes, don't invoke that as per previous user's response. super.onBackPressed();
will onStop
method of the Activity. Instead of onBackPressed();
you can use onKeyDown
for your requirement. If you need to open an AlertDialog
when you press the back button you can simply try that with KeyEvent
For example -
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
AlertDialog.Builder ab = new AlertDialog.Builder(AlertDialogExampleActivity.this);
ab.setMessage("Are you sure?").setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();
break;
}
return super.onKeyDown(keyCode, event);
}
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
break;
case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
break;
}
}
};
When you're overriding onKeyDown
method it will detect back key with your KEYCODE_BACK
Hope this helps you.
Dont invoke super.onBackPressed();
cause it will call onStop method of the activity.
And Displaying a dialog over an activity which has been finished, will leak window.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With