I am trying to make a dialog button that pops up when i am on the main activity and asks the user if they are sure they want to close the program. I’m not sure what to add in the //Action for the Yes button… Is there a better way to do this?
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
alt_bld.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'Yes' Button
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'NO' Button
dialog.cancel();
}
});
AlertDialog alert = alt_bld.create();
// Title for AlertDialog
alert.setTitle("Exit Game?");
// Icon for AlertDialog
alert.setIcon(R.drawable.icon);
alert.show();
return true;
}
return super.onKeyDown(keyCode, event);
}
You can finish Your
Activityfor example. callingfinish()method.Apart from that consider using DialogFragments (if You use compatibility library) or
showDialog()method inActivity– this will prevent leakage of windows.