Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
How to Create Dialog with Custom Layout in Android?
Next article icon

How to Make a Custom Exit Dialog in Android?

Last Updated : 02 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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 don’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. 

Make a Custom Exit Dialog in Android Sample GIF

Approach:

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.

XML

<?xml version="1.0" encoding="utf-8"?>
<resources>
 
   <color name="colorPrimary">#0F9D58</color>
   <color name="colorPrimaryDark">#0F9D58</color>
   <color name="colorAccent">#05af9b</color>
    
</resources>
                      
                       

We also create a  new drawable file (card_round.xml) and also refer to elasq, flaticon for an alert icon, and paste it into the drawable folder. card_round.xml code is shown below

XML

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="8dp" />
    <padding
        android:bottom="8dp"
        android:left="8dp"
        android:right="8dp"
        android:top="8dp" />
</shape>
                      
                       

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

XML

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Press back to exit"
        android:textSize="40dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
 
</androidx.constraintlayout.widget.ConstraintLayout>
                      
                       

Now we create a new layout resource file (custom_exit_dialog.xml) inside it we add an ImageView, TextView, and LinearLayout as shown below as follows:

XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/bottom_sheet_exit_linear"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/card_round"
    android:orientation="vertical">
     
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
         
        <!-- exit the app textview -->
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="00dp"
            android:fontFamily="sans-serif-medium"
            android:gravity="center"
            android:text="Exit The App ?"
            android:textSize="20dp"
            android:textStyle="bold" />
         
        <!-- Alert  Icon  ImageView -->
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="80dp"
            android:layout_marginTop="16dp"
            android:src="@drawable/alert_icon" />
 
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="0dp"
            android:orientation="horizontal"
            android:weightSum="2">
 
            <!-- No  Text View -->
            <TextView
                android:id="@+id/textViewNo"
                android:layout_width="match_parent"
                android:layout_height="48dp"
                android:layout_gravity="center"
                android:layout_margin="8dp"
                android:layout_weight="1"
                android:background="@drawable/card_round"
                android:backgroundTint="#2196F3"
                android:elevation="8dp"
                android:gravity="center"
                android:text="NO"
                android:textColor="@color/white" />
 
            <!-- Yes Text View -->
            <TextView
                android:id="@+id/textViewYes"
                android:layout_width="match_parent"
                android:layout_height="48dp"
                android:layout_gravity="center"
                android:layout_margin="8dp"
                android:layout_weight="1"
                android:background="@drawable/card_round"
                android:backgroundTint="#FD0001"
                android:elevation="8dp"
                android:gravity="center"
                android:text="Yes"
                android:textColor="@color/white" />
             
        </LinearLayout>
         
    </LinearLayout>
 
</LinearLayout>
                      
                       

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

Java

public  void customExitDialog()
    {
        // creating custom dialog
        final Dialog dialog = new Dialog(MainActivity.this);
 
        // setting content view to dialog
        dialog.setContentView(R.layout.custom_exit_dialog);
 
        // getting reference of TextView
        TextView dialogButtonYes = (TextView) dialog.findViewById(R.id.textViewYes);
        TextView dialogButtonNo = (TextView) dialog.findViewById(R.id.textViewNo);
 
        // click listener for No
        dialogButtonNo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // dismiss the dialog
                dialog.dismiss();
 
            }
        });
        // click listener for Yes
        dialogButtonYes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // dismiss the dialog and exit the exit
                dialog.dismiss();
                finish();
 
            }
        });
 
        // show the exit dialog
        dialog.show();
}
                      
                       

Kotlin

fun customExitDialog() {
       // creating custom dialog
       val dialog = Dialog(this@MainActivity)
 
       // setting content view to dialog
       dialog.setContentView(R.layout.custom_exit_dialog)
 
       // getting reference of TextView
       val dialogButtonYes = dialog.findViewById(R.id.textViewYes) as TextView
       val dialogButtonNo = dialog.findViewById(R.id.textViewNo) as TextView
 
       // click listener for No
       dialogButtonNo.setOnClickListener { // dismiss the dialog
           dialog.dismiss()
       }
       // click listener for Yes
       dialogButtonYes.setOnClickListener { // dismiss the dialog and exit the exit
           dialog.dismiss()
           finish()
       }
 
       // show the exit dialog
       dialog.show()
   }
//THis code is written by Ujjwal kumar bhardwaj
                      
                       

Now we call the customExitDialog() method inside the onBackPressed() as shown below

Java

@Override
public void onBackPressed() {
        // calling the function
        customExitDialog();
}
                      
                       

Kotlin

override fun onBackPressed() {
        // calling the function
        customExitDialog()
    }
// This code is written by Ujjwal Kumar Bhardwaj
                      
                       

Below is the complete code for the MainActivity.java file.

Java

import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
 
import androidx.appcompat.app.AppCompatActivity;
 
public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
 
    public void customExitDialog() {
        // creating custom dialog
        final Dialog dialog = new Dialog(MainActivity.this);
 
        // setting content view to dialog
        dialog.setContentView(R.layout.custom_exit_dialog);
 
        // getting reference of TextView
        TextView dialogButtonYes = (TextView) dialog.findViewById(R.id.textViewYes);
        TextView dialogButtonNo = (TextView) dialog.findViewById(R.id.textViewNo);
 
        // click listener for No
        dialogButtonNo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //dismiss the dialog
                dialog.dismiss();
 
            }
        });
         
        // click listener for Yes
        dialogButtonYes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // dismiss the dialog
                // and exit the exit
                dialog.dismiss();
                finish();
 
            }
        });
 
        // show the exit dialog
        dialog.show();
    }
 
    @Override
    public void onBackPressed() {
        // calling the function
        customExitDialog();
    }
}
                      
                       

Kotlin

import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
 
import androidx.appcompat.app.AppCompatActivity;
 
 
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
 
    fun customExitDialog() {
        // creating custom dialog
        val dialog = Dialog(this@MainActivity)
 
        // setting content view to dialog
        dialog.setContentView(R.layout.custom_exit_dialog)
 
        // getting reference of TextView
        val dialogButtonYes = dialog.findViewById(R.id.textViewYes) as TextView
        val dialogButtonNo = dialog.findViewById(R.id.textViewNo) as TextView
 
        // click listener for No
        dialogButtonNo.setOnClickListener(object : OnClickListener() {
            fun onClick(v: View?) {
                //dismiss the dialog
                dialog.dismiss()
            }
        })
 
        // click listener for Yes
        dialogButtonYes.setOnClickListener(object : OnClickListener() {
            fun onClick(v: View?) {
                // dismiss the dialog
                // and exit the exit
                dialog.dismiss()
                finish()
            }
        })
 
        // show the exit dialog
        dialog.show()
    }
 
    override fun onBackPressed() {
        // calling the function
        customExitDialog()
    }
}
// This code is written by Ujjwal Kumar Bhardwaj
                      
                       

Output:

https://media.geeksforgeeks.org/wp-content/uploads/20210327165358/Screenrecorder-2021-03-27-16-51-28-988.mp4


Next Article
How to Create Dialog with Custom Layout in Android?

O

onlyklohan
Improve
Article Tags :
  • Android
  • Java
Practice Tags :
  • Java

Similar Reads

  • How to Implement Custom Dialog Maker in Android?
    In this article, we are going to make an application of Custom Dialog Maker in android studio. In this application, we can create dialogs of our own choice of style, type, and animation. What is a dialog? A dialog is a small window that prompts the user to make a decision, provide some additional in
    5 min read
  • How to Create Dialog with Custom Layout in Android?
    In Android, A dialog is a small window that prompts the user to make a decision, provide some additional information, and inform the user about some particular task. The following are the main purposes or goals of a dialog To warn the user about any activity.To inform the user about any activity.To
    3 min read
  • How to Create CircularDialog in Android?
    CircularDialog is another best way of representing information or data in an Android app. You can get to see these Circular Dialogs in most of the apps which are used to display the message of completion of the process in an attractive form. In this article, we are going to see how to implement Circ
    3 min read
  • How to Customize Toast in Android?
    A Toast is a feedback message. It takes very little space for displaying and it is displayed on top of the main content of an activity, and only remains visible for a short time period. In this article, we will learn how to customize Toast in android. So, we will understand this by making a simple a
    2 min read
  • How to Disable Back Press Button in Android?
    Physical keys on Android let users lock the phone, switch off the device, control volume, go back, go home and display background applications. Between all the keys, the back button is used the most in applications for navigating between activities. However, if the navigation stage reaches the start
    2 min read
  • How to Create a Custom Yes/No Dialog in Android with Kotlin?
    Android AlertDialog is used to display a small window to the user to make a decision via an OK, Yes, or Cancel button or enter additional information. It is normally modal and requires the user to take any action before they can proceed. In this article, we will use AlertDialog to create a reusable
    3 min read
  • How to Enable/Disable Button in Android?
    The Enable/Disable Feature is used in many Android apps so the basic use of that feature is to prevent the user from clicking on a button until they will add all the required fields that have been asked. We are considering an example of email and password if the user has entered the email and passwo
    3 min read
  • How to Manage Audio Focus in Android?
    The audio focus in Android needs to be managed and it is one of the important to handle the audio interruptions. In Android, many applications play media simultaneously, and to increase the User Experience the Audio interruptions are handled. For example, if the application is playing Audio, suddenl
    5 min read
  • How to Display a Yes/No DialogBox in Android?
    DialogBox is used in many android applications to display dialogs. There are different types of dialogs that are displayed within android applications such as AlertDialog, warning dialogs, and others. In this article, we will take a look at How to Display a Yes/No Dialog Box in Android. A sample vid
    4 min read
  • How to Create an Alert Dialog Box in Android?
    An Android Alert Dialog is a UI element that displays a warning or notification message and asks the user to respond with options such as Yes or No. Based on the user's response, appropriate actions are executed. Android Alert Dialog is built with the use of three fields: Title, Message area, and Ac
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences