How to Make a Custom Exit Dialog in Android?
In this tutorial, we are going to create a Custom Exit Dialog in Android. By default, android doesn’t provide any exit dialog, but we can create it using the dialog class in java. But most of the developers and also the user doesn’t like the default dialog box and also we can’t do any modification in the dialog box according to our needs, so in this article, we will create a simple custom exit dialog. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step 1: Creating a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that choose Java as the language though we are going to implement this project in Java language.
Step 2: Before going to the coding section first do some pre-task
Go to app -> res -> values -> colors.xml file and set the colors for the app.
Step 3: Designing the UI
The activity_main.xml contains a default text and we change the text to “Press back to exit ” as shown below
Step 4: Coding Part
Now Open the MainActivity.java file there within the class, first of all, create the function public void customExitDialog() as shown below
Now we call the customExitDialog() method inside the onBackPressed() as shown below
Below is the complete code for the MainActivity.java file.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.