Alert dialog in android studio, alert dialog example, add a dialog in android, custom dialog in android, android alert dialog

Alert dialog in android studio

In android, there are popups that do you usually appear when you want to perform an activity and asks you to either confirm or reject the action. They help the user to ascertain that the action you are performing is not by mistake. They are called alert dialogs in android.

An alert dialog is a floating window that partially obscures the Activity that launched it such that the user must interact with it before proceeding to the next activity.

The alert dialog can either prompts the user to a decision or enter additional information. An android alert dialog is used to display the dialog message with OK and Cancel buttons.

In this article, we shall cover how to include alert dialogs in the android project and also show you an example that is using alert dialogs. An alert dialog is a subclass of the Dialog class. It has three sections, that is, the title, the content area, and the action buttons.

To begin, you will need to note the below methods that are acceptable in the alert dialog class

  • public AlertDialog.Builder setTitle(CharSequence)

This method sets the title of the alert dialog

  • public AlertDialog.Builder setMessage(CharSequence)

This method sets the content in the body section

  • public AlertDialog.Builder setIcon(int)

This method allows you to add a custom icon for your dialog.

The alert dialog does not load by default, it is as a result of action mostly the click of a button.

First, we shall define a button in the XML file. We shall define a logout button

 

<Button
    android:layout_width="200dp"
    android:layout_height="100dp"
    android:id="@+id/logout"
    android:text="Log out"
    android:background="#000"
    android:textColor="#fff"
    android:textSize="30dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

 

The full code for the xml file will be

<?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:layout_width="200dp"
android:layout_height="100dp"
android:id="@+id/logout"
android:text="Log out"
android:background="#000"
android:textColor="#fff"
android:textSize="30dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

 

Next, we will now move to the activity file where we will add the alert dialog

In the import section, import the alert dialog and dialog interface

import android.app.AlertDialog;
import android.content.DialogInterface;

Next, in the public class initialize the alert dialog builder and the logout button

Button logout;
AlertDialog.Builder builder;

Next in the onCreate method call the logout button from the xml file and also instantiate the alert dialog builder

logout = (Button) findViewById(R.id.logout);
builder = new AlertDialog.Builder(this);

Next, add the click activity for the logout button and at this point is where you implement the alert dialog

We will set the content message and set cancellable to false meaning you cannot dismiss the dialog without clicking either the positive or negative button

builder.setMessage("Do you want to logout?")
.setCancelable(false)

Next, we will set the positive button activity action which when you select yes, it will perform the logout activity but in this case, we will show a toast message that you have said you want to logout

.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int id) {
        finish();
        Toast.makeText(getApplicationContext(),"you have chosen to logout",                Toast.LENGTH_SHORT).show();
    }
})

Next, we set the negative button which always have the no or cancel message as follows

.setNegativeButton("No", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int id) {
        //  Action for 'NO' Button
       
dialog.cancel();
        Toast.makeText(getApplicationContext(),"you have chosen not to log out",                Toast.LENGTH_SHORT).show();
    }});

Finally, we will now create the dialog box, set the title, and display the alert dialog

//Creating dialog box
AlertDialog alert = builder.create();
//Setting the title
alert.setTitle("Logout Dialog");
alert.show();

 

The full code for the activity that calls the alert dialog is as follows

package com.example.dialogexample;
import androidx.appcompat.app.AppCompatActivity;\
nimport android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
    Button logout;
    AlertDialog.Builder builder;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        logout = (Button) findViewById(R.id.logout);
        builder = new AlertDialog.Builder(this);
        logout.setOnClickListener(new View.OnClickListener() {
            @Override
        public void onClick(View v) {
            builder.setMessage("Do you want to logout?")
                    .setCancelable(false)
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            finish();
                            Toast.makeText(getApplicationContext(),"you have chosen to logout",
                                    Toast.LENGTH_SHORT).show();
                        }
                    })                    .setNegativeButton("No", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            //  Action for 'NO' Button
                           
dialog.cancel();
                            Toast.makeText(getApplicationContext(),"you have chosen not to log out",
                                    Toast.LENGTH_SHORT).show();
                        }
                    });            //Creating dialog box
           
AlertDialog alert = builder.create();
            //Setting the title
           
alert.setTitle("Logout Dialog");
            alert.show();
        }
    });
}}