How to handle the back button in a dialog box?

I am developing an application that, when pressed, opens a dialog with the "OK" and "Cancel" buttons.

It works great.

When the user clicks the back button, I process it as follows

public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK)) { } return super.onKeyDown(keyCode, event); } 

But the above method is not called. How can I handle this?

+76
android button dialog back
Apr 27 2018-12-12T00
source share
5 answers
 dialog.setOnKeyListener(new Dialog.OnKeyListener() { @Override public boolean onKey(DialogInterface arg0, int keyCode, KeyEvent event) { // TODO Auto-generated method stub if (keyCode == KeyEvent.KEYCODE_BACK) { finish(); dialog.dismiss(); } return true; } }); 
+179
Feb 01 '13 at 13:08
source share

It looks like you want to install OnCancelListener when creating the dialog box. It looks like this:

 dialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { //do whatever you want the back key to do } }); 
+86
Apr 27 '12 at 7:22
source share

You need to override the OnCancel method. This method calls the back key. Here's a code that works great for me.

  AlertDialog alertDialog; alertDialog.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { // TODO Auto-generated method stub dialog.dismiss(); } }); 

I hope this helps you and will accept it if it is useful to you.

Thank..

+19
Apr 27 '12 at 7:20
source share

try it

  new AlertDialog.Builder(this).setOnKeyListener(new DialogInterface.OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK){ Logger.d(TAG, "--------- Do Something -----------"); return true; } return false; } }) 
+4
Apr 27 '12 at 6:50
source share

this is because when a dialog box opens, your window moves in the dialog box. So now you have to handle key in the dialog box.

+1
Apr 27 '12 at 6:50
source share



All Articles