Display Alert on Back button pressed in Android Studio

Some time in your application, it is needed to prompt user before taking back him to previous page or exit from application. In this article, we will see how you can prompt user on pressing back button.

Alert means to get user’s input when needed. Most of us played games and when we try to exit it by pressing “Back” button in Android phone, it ask for “Do you really want to exit?”.

So, in this article we are going to learn how to prevent user to exit from application without giving response.

Step 1

Create a new Project with following parameters.

alert back press 1

Step 2

Open your Main Activity file, in my case it is BackPressActivity.java and paste following code inside.

Let’s understand Alert Dialog and its different methods.

  1. builder.setCancelable(false); which means that user can’t cancel this dialog by pressing back again or touch outside the alert dialog box and dismiss it. So user has to press one of the options you have provided to him.
  2. builder.setMessage(“Do you want to Exit?”); Here you can write your own message which will be displayed to user in alert.
  3. builder.setPositiveButton will set a positive button in left side. Parameter will accept the name of that button as you can see in code is “Yes”.
  4. builder.setNegativeButton will set a negative button in right side. Parameter will accept the name of that button as you can see in code is “No”

When you set this button, you need to pass a listener which will be fired when user click one of the button.

Step 3

Run your application.

Summary

In this article, we learned “How to show Alert Dialog” and “Show dialog at BACK button pressed”.

You may also like to read

Develop apps faster using Data Binding – Par... Google has been pushing updates to existing tools and making the life of android developers easier. They also have been releasing new libraries and AP...
MaxHeightScrollView in Android using Android Studi... In Android, there are two constants for providing height and width of any view. But if you provide any specific height to any view, it won't be change...
Create custom Toast in Android Studio In this article we learn how to create Custom Toast in Android Studio. Toast A Toast provides simple feedback in a small popup about an operatio...
Using Facebook’s Shimmer effect in Android &... In this tutorial, you will learn how to implement "Shimmer effect" developed by Facebook in RecyclerView for Android. In Facebook, you see that un...
Share on Facebook0Share on Google+4Tweet about this on TwitterShare on LinkedIn0Share on Reddit0Pin on Pinterest0Share on Tumblr0Email this to someone