Override the following method of Activity to add Key event into Android Application.
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
AlertDialog.Builder alertbox = new AlertDialog.Builder(HomeActivity.this);
alertbox.setIcon(R.drawable.info_icon);
alertbox.setTitle("You Want To Exit Programm");
alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// finish used for destroyed activity
finish();
}
});
alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// Nothing will be happened when clicked on no button
// of Dialog
}
});
alertbox.show();
}
return super.onKeyDown(keyCode, event);
}
2 Comments
Nice snippet.
ReplyDeleteI have also another solution to display alert on back pressed. I write an article on same. Please visit http://chintanrathod.com/display-alert-on-back-button-pressed-in-android-studio/
It is not working,I want it to be worked for a fragment
ReplyDelete