Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dismiss dialog and close activity in single back press

Tags:

android

I am showing dialog on activity start with:

mDialog.setCanceledOnTouchOutside(false);

When user press the back button, its first dismiss the dialog and then on again press on back button it close the activity. I want to do this in single back press, close the dialog and close activity. I have tried wit the following code also:

@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);
    }
like image 685
Deepak Avatar asked Dec 31 '15 10:12

Deepak


2 Answers

Set a mDialog.setOnCancelListener(listener) and close the Activity in that listener.

@Override
mDialog.setOnCancelListener(new OnCancelListener() {

    public void onCancel(DialogInterface interface) {
        this.finish();            
    }
});

Alternatively you could use a OnKeyListener for your 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;
        }
    });
like image 38
Niels Masdorp Avatar answered Sep 23 '22 12:09

Niels Masdorp


Use OnCancelListener

alertDialog.setOnCancelListener(new OnCancelListener() {

    public void onCancel(DialogInterface dialog) {
        // finish activity             
    }
});
like image 159
Jaiprakash Soni Avatar answered Sep 21 '22 12:09

Jaiprakash Soni