Learn how to implement dialogs in Android with the Sweet Alert styles.

How to use Sweet Alert Dialogs in Android

For web developers, the Sweet Alert library is an example of how flat style can be mixed with almost any kind of user interface. Although the library has been originally designed for web applications, someone out there (@pedant) decided to implement a native port of this library to Android. However, the library isn't maintained anymore officially (works alright, but for lower targetSdkVersions), so for those who use the library in newer versions of Android will be unable to use it if you use the version of the official repository. Instead, to provide support for the latest versions of Android, you can use a forked version maintained by @F0RIS.

In this article, we'll show you how to install and use the Android port of the Sweet Alert library to create and use beautiful flat dialogs in your mobile application.

1. Install Sweet Alert Dialog library

Sweer Alert for android is a beautiful and clever alert dialog library, based on the Sweet Alert library made for JavaScript. Pitifully, the official library isn't maintained anymore and the installation of the library in recent Android Studio versions with higher targetSdkVersion it will fail. That's why instead of installing the original package , we will use the maintained fork by F0RIS (This is the most advanced and contemporary fork of the apparently dead project). You can install this plugin through gradle adding the implementation in the build.gradle file:

dependencies {
    implementation 'com.github.f0ris.sweetalert:library:1.5.6'
}

After adding the dependency, synchronize the project. With this library, you will need to have at least the minSdkVersion set to 13 and targetSdkVersion to 27. For more information about this library, please visit the official repository at Github here.

2. Using the library

With Sweet Alert, you will be able to display 6 types of dialogs namely for every ocassion:

  1. Success
  2. Warning
  3. Error
  4. Information
  5. Loading
  6. Confirmation

You just need to import the namespace on the class where you need it and create a new instance of SweetAlertDialog, define custom properties and attach some onClick listeners to do something according to the selected option by the user:

// Import library
import cn.pedant.SweetAlert.SweetAlertDialog;
import android.graphics.Color;

// 1. Success message
new SweetAlertDialog(MainActivity.this)
    .setTitleText("Here's a message!")
    .show();

// 2. Confirmation message
new SweetAlertDialog(MainActivity.this, SweetAlertDialog.WARNING_TYPE)
    .setTitleText("Are you sure?")
    .setContentText("You won't be able to recover this file!")
    .setConfirmText("Delete!")
    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
        @Override
        public void onClick(SweetAlertDialog sDialog) {
            sDialog.dismissWithAnimation();
        }
    })
    .setCancelButton("Cancel", new SweetAlertDialog.OnSweetClickListener() {
        @Override
        public void onClick(SweetAlertDialog sDialog) {
            sDialog.dismissWithAnimation();
        }
    })
    .show();

// 3. Error message
new SweetAlertDialog(MainActivity.this, SweetAlertDialog.ERROR_TYPE)
        .setTitleText("Oops...")
        .setContentText("Something went wrong!")
        .show();

// 4. Loading message
SweetAlertDialog pDialog = new SweetAlertDialog(MainActivity.this, SweetAlertDialog.PROGRESS_TYPE);
        pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
        pDialog.setTitleText("Loading ...");
        pDialog.setCancelable(true);
        pDialog.show();

// 5. Confirm success
new SweetAlertDialog(MainActivity.this, SweetAlertDialog.WARNING_TYPE)
    .setTitleText("Are you sure?")
    .setContentText("Won't be able to recover this file!")
    .setConfirmText("Yes,delete it!")
    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
        @Override
        public void onClick(SweetAlertDialog sDialog) {
            sDialog
                .setTitleText("Deleted!")
                .setContentText("Your imaginary file has been deleted!")
                .setConfirmText("OK")
                .setConfirmClickListener(null)
                .changeAlertType(SweetAlertDialog.SUCCESS_TYPE);
        }
    })
    .show();

Full example

In the activity_main.xml file we will have the following layout that contains basically 5 buttons, every of them with an identifier that will be used later in the code to attach the onClick event:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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/successButton"
        android:layout_width="wrap_content"
        android:layout_height="49dp"
        android:text="Success"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.049"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.023" />

    <Button
        android:id="@+id/confirmationButton"
        android:layout_width="wrap_content"
        android:layout_height="49dp"
        android:text="Confirm"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.95"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.023" />

    <Button
        android:id="@+id/errorButton"
        android:layout_width="wrap_content"
        android:layout_height="49dp"
        android:text="Error"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.023" />

    <Button
        android:id="@+id/loadingButton"
        android:layout_width="159dp"
        android:layout_height="49dp"
        android:text="Loading ..."
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.054"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.143" />

    <Button
        android:id="@+id/confirmSuccessButton"
        android:layout_width="wrap_content"
        android:layout_height="49dp"
        android:text="Confirm Success"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.938"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.143" />
</android.support.constraint.ConstraintLayout>

The code to test the Sweet Alert dialog is:

package com.yourcompany.yourapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

// Import library
import cn.pedant.SweetAlert.SweetAlertDialog;
import android.graphics.Color;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 1. Success message
        Button buttonSuccess = findViewById(R.id.successButton);
        buttonSuccess.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                new SweetAlertDialog(MainActivity.this)
                    .setTitleText("Here's a message!")
                    .show();
            }
        });

        // 2. Confirmation message
        Button buttonWarning = findViewById(R.id.confirmationButton);
        buttonWarning.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                new SweetAlertDialog(MainActivity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("Are you sure?")
                    .setContentText("You won't be able to recover this file!")
                    .setConfirmText("Delete!")
                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sDialog) {
                            sDialog.dismissWithAnimation();
                        }
                    })
                    .setCancelButton("Cancel", new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sDialog) {
                            sDialog.dismissWithAnimation();
                        }
                    })
                    .show();
            }
        });

        // 3. Error message
        Button buttonDanger = findViewById(R.id.errorButton);
        buttonDanger.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                new SweetAlertDialog(MainActivity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("Oops...")
                    .setContentText("Something went wrong!")
                    .show();
            }
        });

        // 4. Loading message
        Button buttonLoading = findViewById(R.id.loadingButton);
        buttonLoading.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                SweetAlertDialog pDialog = new SweetAlertDialog(MainActivity.this, SweetAlertDialog.PROGRESS_TYPE);
                pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
                pDialog.setTitleText("Loading ...");
                pDialog.setCancelable(true);
                pDialog.show();
            }
        });

        // 5. Confirm success
        Button buttonConfirmSuccess = findViewById(R.id.confirmSuccessButton);
        buttonConfirmSuccess.setOnClickListener(new View.OnClickListener() {
            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!")
                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sDialog) {
                            sDialog
                                .setTitleText("Deleted!")
                                .setContentText("Your imaginary file has been deleted!")
                                .setConfirmText("OK")
                                .setConfirmClickListener(null)
                                .changeAlertType(SweetAlertDialog.SUCCESS_TYPE);
                        }
                    })
                    .show();
            }
        });
    }
}

Happy coding !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors