The onBackPressed() method is responsible for processing when the Back button is pressed in the activity.
@Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Closing Activity")
.setMessage("Are you sure you want to close this activity?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
When the Back button is pressed, a dialog is created When the OK button is clicked, call the method finish() to end the activity.
© 2024 OneMinuteCode. All rights reserved.