Open In App

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

Last Updated : 09 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
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:

  • 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 File

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

implementation 'com.github.f0ris.sweetalert:library:1.5.1'

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.

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    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:onClick="showDialog"
        android:text="Basic Dialog"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.452"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.124" />
  
    <Button
        android:id="@+id/error_dialog"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="showDialog"
        android:text="Error Dialog"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.452"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.284" />
  
    <Button
        android:id="@+id/warning_dialog"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="showDialog"
        android:text="Warning Dialog"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.452"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.45" />
  
    <Button
        android:id="@+id/success_dialog"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="256dp"
        android:onClick="showDialog"
        android:text="Success Dialog"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.47"
        app:layout_constraintStart_toStartOf="parent" />
  
    <Button
        android:id="@+id/custom_dialog"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="156dp"
        android:onClick="showDialog"
        android:text="Custom Dialog"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.464"
        app:layout_constraintStart_toStartOf="parent" />
</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.

Java




import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import cn.pedant.SweetAlert.SweetAlertDialog;
  
public class MainActivity extends AppCompatActivity {
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
  
    public void showDialog(View view) {
        switch (view.getId()) {
            case R.id.basic_dialog:
                new SweetAlertDialog(this)
                        .setTitleText("Here's a message!")
                        .setContentText("This is Basic Dialog").show();
                break;
  
            case R.id.error_dialog:
                new SweetAlertDialog(this, SweetAlertDialog.ERROR_TYPE)
                        .setTitleText("Oops...")
                        .setContentText("Something went wrong!").show();
                break;
  
            case R.id.warning_dialog:
                new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("Are you sure?")
                        .setContentText("Won't be able to recover this file !")
                        .setConfirmText("Yes, delete it!").show();
                break;
  
            case R.id.success_dialog:
                new SweetAlertDialog(this, SweetAlertDialog.SUCCESS_TYPE)
                        .setTitleText("Great!")
                        .setContentText("You completed this task.").show();
                break;
  
            case R.id.custom_dialog:
                new SweetAlertDialog(this, SweetAlertDialog.CUSTOM_IMAGE_TYPE)
                        .setTitleText("Android")
                        .setContentText("This is custom dialog")
                        .setCustomImage(R.drawable.ic_android_black).show();
                break;
        }
    }
}


Kotlin




import android.os.Bundle
import android.view.View
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)
    }
  
    fun showDialog(view: View) {
        when (view.id) {
            R.id.basic_dialog -> SweetAlertDialog(this)
                .setTitleText("Here's a message!")
                .setContentText("This is Basic Dialog").show()
  
            R.id.error_dialog -> SweetAlertDialog(this,
                SweetAlertDialog.ERROR_TYPE).setTitleText("Oops...")
                .setContentText("Something went wrong!").show()
  
            R.id.warning_dialog -> SweetAlertDialog(this,
                SweetAlertDialog.WARNING_TYPE).setTitleText("Are you sure?")
                .setContentText("Won't be able to recover this file !")
                .setConfirmText("Yes, delete it!").show()
  
            R.id.success_dialog -> SweetAlertDialog(this,
                SweetAlertDialog.SUCCESS_TYPE).setTitleText("Great!")
                .setContentText("You completed this task.").show()
  
            R.id.custom_dialog -> SweetAlertDialog(this,
                SweetAlertDialog.CUSTOM_IMAGE_TYPE).setTitleText("Android")
                .setContentText("This is custom dialog")
                .setCustomImage(R.drawable.ic_android_black).show()
        }
    }
}


Output:



Similar Reads

How to Create Progress Dialog Using ProgressBar and AlertDialog in Android?
In Android, a Progress bar is a UI element used to display the progress of any running task or an operation. An Alert Dialog is a type of alert message displayed over the screen that lets users choose between options to respond to the message of the alert. Both of these elements are different from each other in nature and in serving a purpose. Howe
3 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 is generally titled "cancel" or "no" or "continue"
3 min read
How to Create a Custom AlertDialog in Android?
Sometimes in AlertDialog, there is a need to get input from the user or customize it according to our requirements. So we create custom AlertDialogs. This post will show how to customize the AlertDialogs and take input from it. Below is the step-by-step implementation of the above approach: Step 1: Create an XML file custom_layout.xml Add the below
2 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 overlaying box in the center of the screen. However, we can
2 min read
How to Create an Alert Dialog Box in Android?
Alert Dialog shows the Alert message and gives the answer in the form of yes or no. Alert Dialog displays the message to warn you and then according to your response, the next step is processed. Android Alert Dialog is built with the use of three fields: Title, Message area, and Action Button. Alert Dialog code has three methods:setTitle() method f
4 min read
How to Display Dynamic AlertDialog in Android using Firebase Firestore?
Dynamic AlertDialog is used in many different apps which are used to show different messages from dialog to the users. This type of dialog is also used for educating users with so many promotional banners. This type of alert dialog is generally dynamic and it displays images and texts which are dynamic in behavior and change after a certain interva
7 min read
AlertDialog in Android using Jetpack Compose
AlertDialog shows the Alert message and gives the answer in the form of yes or no. Alert Dialog displays the message to warn you and then according to your response, the next step is processed. Android Alert Dialog is built with the use of three fields: Title, Message area, Action Button. We have seen AlertDialog in many of the apps, this is used t
4 min read
How to Exit an App Using an AlertDialog in Android?
An AlertDialog in Android is a kind of message displayed to let the user choose an action. This message generally appears as an overlay in the center of the screen with a title, a message, and two Buttons: a positive button and a negative button. A sample Alert Dialog is shown in the below image. In many modern-day applications, we get an AlertDial
2 min read
How to Change the Position of AlertDialog in Android?
AlertDialog in android is one of the UI widgets which immediately pops up to confirm the user interaction or to confirm the action which is done by the user. In most of the applications, the position of the alert dialog in the center. In this article, it's been discussed how to change the position of the alert dialog in android. Have a look at the
4 min read
How to Customize AlertDialog Dimensions in Android?
AlertDialog in Android is a kind of pop-up message that alerts the user about the activity usages. This is specifically developed by a developer to perform any operations or ask for any permissions and not an Android OS call. Alert Dialog in general has no fixed dimension values and rather varies from device to device depending upon the application
3 min read
Article Tags :
Practice Tags :