Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • Java
  • Android
  • Kotlin
  • Flutter
  • Dart
  • Android with Java
  • Android Studio
  • Android Projects
  • Android Interview Questions
Open In App
Next Article:
How to Create AlertDialog Box Using SweetAlert Dialog Library in Android?
Next article icon

How to Create AlertDialog Box Using SweetAlert Dialog Library in Android?

Last Updated : 10 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will learn about how to add Custom Alert Dialog in an app using the SweetAlert Dialog Library. It is a pop-up box that appears in response to any action of the user. AlertBox is very useful when it comes to validation, it can be used to display confirmation messages. Suppose the user presses the Back Button without saving the changes then for warning it can be used. When the transaction is done in payment apps a short Dialog Box can be shown to the user describing the transaction's status.

Advantages of AlertDialog Box

  • It provides us with an excellent user interface which makes the user experience very good.
  • It makes the work much easier so it is used over Custom Dialog, which needs the whole layout to be created.
  • It provides many different types of layouts for the dialog box.

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.

The code for that has been given in both Java and Kotlin Programming Language for Android.


Step 2: Adding Dependency to the build.gradle.kts File

 Go to Module build.gradle.kts file and add this dependency and click on Sync Now button.

implementation ("com.github.f0ris.sweetalert:library:1.6.2")


Step 3: Working with the XML Files

Next, go to the activity_main.xml file, which represents the UI of the project. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail.

activity_main.xml:

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">      <Button         android:id="@+id/basic_dialog"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:backgroundTint="@android:color/holo_green_dark"         android:text="Basic Dialog"         app:layout_constraintBottom_toTopOf="@+id/error_dialog"         app:layout_constraintEnd_toEndOf="parent"         app:layout_constraintStart_toStartOf="parent"         app:layout_constraintTop_toTopOf="parent" />      <Button         android:id="@+id/error_dialog"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:backgroundTint="@android:color/holo_green_dark"         android:text="Error Dialog"         app:layout_constraintBottom_toTopOf="@+id/warning_dialog"         app:layout_constraintEnd_toEndOf="parent"         app:layout_constraintStart_toStartOf="parent"         app:layout_constraintTop_toBottomOf="@+id/basic_dialog" />      <Button         android:id="@+id/warning_dialog"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:backgroundTint="@android:color/holo_green_dark"         android:text="Warning Dialog"         app:layout_constraintBottom_toTopOf="@+id/success_dialog"         app:layout_constraintEnd_toEndOf="parent"         app:layout_constraintStart_toStartOf="parent"         app:layout_constraintTop_toBottomOf="@+id/error_dialog" />      <Button         android:id="@+id/success_dialog"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:backgroundTint="@android:color/holo_green_dark"         android:text="Success Dialog"         app:layout_constraintBottom_toTopOf="@+id/custom_dialog"         app:layout_constraintEnd_toEndOf="parent"         app:layout_constraintStart_toStartOf="parent"         app:layout_constraintTop_toBottomOf="@+id/warning_dialog" />      <Button         android:id="@+id/custom_dialog"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:backgroundTint="@android:color/holo_green_dark"         android:text="Custom Dialog"         app:layout_constraintBottom_toBottomOf="parent"         app:layout_constraintEnd_toEndOf="parent"         app:layout_constraintStart_toStartOf="parent"         app:layout_constraintTop_toBottomOf="@+id/success_dialog" /> </androidx.constraintlayout.widget.ConstraintLayout> 


Step 4: Working with the MainActivity File

Go to the MainActivity File and refer to the following code. Below is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail.

MainActivity.java
package org.geeksforgeeks.demo;  import android.os.Bundle; import android.view.View; import android.widget.Button; import androidx.appcompat.app.AppCompatActivity; import cn.pedant.SweetAlert.SweetAlertDialog;  // Main Method public class MainActivity extends AppCompatActivity {      // Overriding onCreate Method     @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          // Buttons connected          Button basicDialog = findViewById(R.id.basic_dialog);         Button errorDialog = findViewById(R.id.error_dialog);         Button warningDialog = findViewById(R.id.warning_dialog);         Button successDialog = findViewById(R.id.success_dialog);         Button customDialog = findViewById(R.id.custom_dialog);          // Buttons Clicked Listener are setted below                  basicDialog.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View v) {                 new SweetAlertDialog(MainActivity.this)                         .setTitleText("Here's a message!")                         .setContentText("This is Basic Dialog")                         .show();             }         });          errorDialog.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View v) {                 new SweetAlertDialog(MainActivity.this, SweetAlertDialog.ERROR_TYPE)                         .setTitleText("Oops...")                         .setContentText("Something went wrong!")                         .show();             }         });          warningDialog.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View v) {                 new SweetAlertDialog(MainActivity.this, SweetAlertDialog.WARNING_TYPE)                         .setTitleText("Are you sure?")                         .setContentText("Won't be able to recover this file!")                         .setConfirmText("Yes, delete it!")                         .show();             }         });          successDialog.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View v) {                 new SweetAlertDialog(MainActivity.this, SweetAlertDialog.SUCCESS_TYPE)                         .setTitleText("Great!")                         .setContentText("You completed this task.")                         .show();             }         });          customDialog.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View v) {                 new SweetAlertDialog(MainActivity.this, SweetAlertDialog.CUSTOM_IMAGE_TYPE)                         .setTitleText("Android")                         .setContentText("This is custom dialog")                         .setCustomImage(R.mipmap.ic_launcher_round)                         .show();             }         });     } } 
MainActivity.kt
package org.geeksforgeeks.demo  import android.os.Bundle import android.widget.Button import androidx.appcompat.app.AppCompatActivity import cn.pedant.SweetAlert.SweetAlertDialog  class MainActivity : AppCompatActivity() {      override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         setContentView(R.layout.activity_main)          // Buttons Connected         val basicDialog: Button = findViewById(R.id.basic_dialog)         val errorDialog: Button = findViewById(R.id.error_dialog)         val warningDialog: Button = findViewById(R.id.warning_dialog)         val successDialog: Button = findViewById(R.id.success_dialog)         val customDialog: Button = findViewById(R.id.custom_dialog)          // Buttons Clicked Listener are setted below                  basicDialog.setOnClickListener {             SweetAlertDialog(this)                 .setTitleText("Here's a message!")                 .setContentText("This is Basic Dialog").show()         }         errorDialog.setOnClickListener {             SweetAlertDialog(this,                 SweetAlertDialog.ERROR_TYPE).setTitleText("Oops...")                 .setContentText("Something went wrong!").show()         }         warningDialog.setOnClickListener {             SweetAlertDialog(this,                 SweetAlertDialog.WARNING_TYPE).setTitleText("Are you sure?")                 .setContentText("Won't be able to recover this file !")                 .setConfirmText("Yes, delete it!").show()         }         successDialog.setOnClickListener {             SweetAlertDialog(this,                 SweetAlertDialog.SUCCESS_TYPE).setTitleText("Great!")                 .setContentText("You completed this task.").show()         }         customDialog.setOnClickListener {             SweetAlertDialog(this,                 SweetAlertDialog.CUSTOM_IMAGE_TYPE).setTitleText("Android")                 .setContentText("This is custom dialog")                 .setCustomImage(R.mipmap.ic_launcher_round).show()         }     } } 

Output:


Next Article
How to Create AlertDialog Box Using SweetAlert Dialog Library in Android?

M

madhavmaheshwarimm20
Improve
Article Tags :
  • Java
  • Kotlin
  • Android
  • DSA
  • Kotlin Android
  • Java-Android
Practice Tags :
  • Java

Similar Reads

    How to create popup message using Alerter Library in android
    In this article, we learn about how to create a popup message with the help of Alerter Library. It is better to use Alerter than using Toast or Snackbar in cases if some alert messages are to be displayed to the user. We can add various onClickListners to our alerter message which makes it better an
    2 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
    How to Create a Full Screen AlertDialog in Android?
    AlertDialog in Android is an alert message programmatically displayed to the user over the change of course of action. This appears as a pop-up and has four elements i.e., a title, a message, a positive button, and a negative button. Typically, AlertDialog is non-customized and appears as an overlay
    2 min read
    How to Prevent AlertDialog Box From Closing in Android?
    In Android, AlertDialog is a simple alert message that appears in the form of a pop-up that consists of a title, a message, and two buttons namely positive and negative buttons. The user basically has to click on one of the two buttons to reply to the message in the AlertDialog. The negative button
    3 min read
    How to Close Alert Dialog Box in Android Programmatically?
    AlertDialog is a flash or an alert message with options that let the user proceed or deny any process or action. AlertDialog generally consists of the main title, the message, and two buttons, technically termed as a positive button and a negative button. Both positive and negative buttons can be pr
    2 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