Reputation: 4216
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);
}
Upvotes: 1
Views: 2874
Reputation: 1932
you can use simple finish() statement in you action of yes Button to exit from activity
and you can also override onBackPressed method for that
Upvotes: 1
Reputation: 26441
You can finish Your Activity
for example. calling finish()
method.
Apart from that consider using DialogFragments (if You use compatibility library) or showDialog()
method in Activity
- this will prevent leakage of windows.
Upvotes: 3