Reputation: 71
I have a single activity. When the user wants to close this activity using the back-button, I want to display a dialog, whether the user is sure and some other options.
Overriding the button is not problem, but really finishing the app from the dialog is the issue.
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
Log.i(tag, "Pushed BACK button by onKeyDown");
}
try {
showFinishDialog();
return super.onKeyDown(keyCode, event);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return super.onKeyDown(keyCode, event);
}
}
This opens the dialog (showFinishDialog()), but I do not know what to call within the dialog to finally really finish my activity. I tried public functions like onBackPressed and onDestroy, but no success.
Thanks ahead!
Upvotes: 1
Views: 904
Reputation: 25858
Just write down
finish();
wherever you want to finish your activity.
Like if you want to finish on a button click
@Override
public void onClick(DialogInterface dialog, int id) {
finish();
}
Upvotes: 0
Reputation: 10059
Override onBackPressed()
. You can achieve your goal by following code which overrides the back button and popup the dialog box.
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//Do your coding here. For Positive button
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
Hope it helps.
Upvotes: 2