Reject the dialog and close the activity in a single click back

I show the start activity dialog with:

mDialog.setCanceledOnTouchOutside(false); 

When the user clicks the back button, first rejects the dialog box and then clicks the back button again to close the action. I want to do this with one click, close the dialog and close the activity. I also tried using the following code:

 @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // TODO Auto-generated method stub if (keyCode == KeyEvent.KEYCODE_BACK) { // AppDialogUtils.mDialog.setCancelable(true); // AppDialogUtils.mDialog.dismiss(); mActivity.finish(); } return super.onKeyDown(keyCode, event); } 
+5
source share
5 answers

Install mDialog.setOnCancelListener(listener) and close the Activity in this listener.

 @Override mDialog.setOnCancelListener(new OnCancelListener() { public void onCancel(DialogInterface interface) { this.finish(); } }); 

Alternatively, you can use OnKeyListener for Dialog .

 mDialog.setOnKeyListener(new Dialog.OnKeyListener() { @Override public boolean onKey(DialogInterface interface, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { this.finish(); } return true; } }); 
+9
source

Use OnCancelListener

 alertDialog.setOnCancelListener(new OnCancelListener() { public void onCancel(DialogInterface dialog) { // finish activity } }); 
+2
source

if your dialog box is open, then

 dialog.dismiss(); 

this will cancel your dialog and if you want to click back use this line

 @Override public void onBackPressed() { super.onBackPressed(); finish(); } 

it will work for you

0
source

this might work for you.

at first i don't think it works

 mDialog.setCanceledOnTouchOutside(false); 

you can use

 dialog.setCancelable(false); 

Now his work is how you like.

-2
source

onBackPressed() event and cancel the dialog and action in the same function.

 @Override public void onBackPressed() { dialog.dismiss(); finish(); } 
-3
source

Source: https://habr.com/ru/post/1239569/


All Articles