Show Exit Confirm Dialog When Press ‘Back’ Button


@Override
public boolean onKeyDown(int keyCode, KeyEvent event) { // this is override method
if(keyCode == KeyEvent.KEYCODE_BACK){
showExitConfirmDialog(); // call the function below
}
return super.onKeyDown(keyCode, event);
}

public void showExitConfirmDialog(){ // just show an dialog
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Exit?"); // set title
dialog.setMessage("Are you sure to exit?"); // set message
dialog.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
MainActivity.this.finish(); // when click OK button, finish current activity!
}
});
dialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getBaseContext(), "Cancelled", Toast.LENGTH_SHORT).show(); // just show a Toast, do nothing else
}
});
dialog.create().show();
}

Advertisements

One thought on “Show Exit Confirm Dialog When Press ‘Back’ Button

  1. Pingback: Android | David Ng

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s