Deepak
Deepak

Reputation: 1676

Dismiss dialog and close activity in single back press

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);
    }

Upvotes: 10

Views: 10153

Answers (6)

Annsh Singh
Annsh Singh

Reputation: 435

Make sure you have set mDialog.setCancelable(true) then set

mDialog.setOnCancelListener {
                    this.finish()
                }

Note: This is the lambda function for the setOnCancelListener.

Upvotes: 1

Niels Masdorp
Niels Masdorp

Reputation: 2428

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;
        }
    });

Upvotes: 22

Kinjal Patel
Kinjal Patel

Reputation: 105

this may works for you.

first I don't think this one works

mDialog.setCanceledOnTouchOutside(false);

you can use

dialog.setCancelable(false);

now its works as you wanted.

Upvotes: -1

Noor Ahmed
Noor Ahmed

Reputation: 1617

Overload the activity's onBackPressed() event and dismiss the dialog and activity in the same function.

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

Upvotes: -2

Amitsharma
Amitsharma

Reputation: 1578

if your dialog is open then

dialog.dismiss();

this will make dismiss your dialog and if you want to press back then use this line

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

this will work for you

Upvotes: -1

Jaiprakash Soni
Jaiprakash Soni

Reputation: 4112

Use OnCancelListener

alertDialog.setOnCancelListener(new OnCancelListener() {

    public void onCancel(DialogInterface dialog) {
        // finish activity             
    }
});

Upvotes: 4

Related Questions