I want to display a dialog so that the activity ends if the user agrees.

Asked 2 years ago, Updated 2 years ago, 75 views

When the user presses the back button, the user displays a dialog saying "Do you want to end?" and checks it I'd like to end the activity. The only thing I know about is Activity.onUserLeaveHint(). What should I do?

android dialog

2022-09-21 17:33

1 Answers

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.


2022-09-21 17:33

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.