Alert Dialog And Custom Dialog For Android

Custom Alertbox for Android

A Dialog is a small window that prompts the user to a decision or enter additional information.

Some times in our application, if you wanted to ask the user about deciding between yes or no in response to any particular action taken by the user, by remaining in the same activity and without changing the screen, you can use Alert Dialog.

Objectives of this Tutorial

https://youtu.be/7w5K6ed2MLY

1

Creating a simple Alert Dialog using AlertDialog.Builder.

2

Creating a Custom Dialog with Custom Layout.

In this example, we will devolve Alert Dialog and Custom Dialog.

How to create Alert Dialog

To create an alert dialog, make an object of AlertDialogBuilder which is an inner class of AlertDialog.

The following syntax is used to create alert dialog:

1. AlertDialog.Builder(Context context)

Create a builder for an alert dialog that uses the default alert dialog theme.

Syntax:

AlertDialog.Builder object = new AlertDialog.Builder (Context context);

For example:

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Mainactivity.this);

2. AlertDialog.Builder(Context context, int themeResId)

Create a builder for an alert dialog that uses an explicit theme resource.

Syntax:

AlertDialog.Builder object = new AlertDialog.Builder (Context context,int themeResId);

For example:

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Mainactivity.this,R.style.dialogTheme);

Important method and description of Alert Dialog

1. setIcon(Drawable icon)

This method is used to set the icon of the alert dialog box.

2. setCancelable(boolean cancelable)

This method is used to set the property that the dialog can be canceled or not.

3. setMessage(CharSequence message)

This method sets the message to be displayed in the alert dialog.

4. setTitle(CharSequence title)

This method used to set the title to appear in the dialog.

5. setNegativeButton(CharSequence text, DialogInterface.OnClickListener listener)

This method is used to set a listener to be invoked when the negative button of the dialog is pressed.

6. setPositiveButton(CharSequence text, DialogInterface.OnClickListener listener)

This method is used to set a listener to be invoked when the positive button of the dialog is pressed.

7. show()

This method is used to create an AlertDialog with the arguments supplied to this builder and immediately displays the dialog.

8. setOnDismissListener(DialogInterface.OnDismissListener onDismissListener)

This method is used to set the callback that will be called when the dialog is dismissed for any reason.

For more information visit: https://developer.android.com/reference/android/app/AlertDialog.Builder.html

Example of how to create alert dialog

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); // create the object of alert dialog
        builder.setTitle(“TITLE"); // set the title of alert dialog using setTitle() method 
        builder.setMessage("THIS IS ALERT DIALOG DEMO”); //the msg with alert dialog using setMessage() method
        // now set the postive button with alert dialog and handle it result using setPositiveButton() method
        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this, "Ok Button Clicked", Toast.LENGTH_SHORT).show();
            }
        });
        // now set the negative button with alert dialog and handle it result using setNegativeButton() method
        builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toast.makeText(MainActivity.this, "Cancel Button Clicked", Toast.LENGTH_SHORT).show();
            }
        });
        builder.show();// now show the alert dialog using show() method

How to create a custom dialog with custom layout

To create a custom dialog, make an object of Dialog which an inner class of Dialog

The following syntax is used to create custom dialog

1. Dialog (Context context);

Create an object for a custom dialog that uses the default dialog theme.

Syntax:

Dialog object = new Dialog (Context context);

For example:

Dialog customDialog = new Dialog(MainActivity.this);

2. Dialog (Context context, int themeResId)

Create an object for a custom dialog that uses an explicit theme resource.

Syntax:

Dialog object = new Dialog (Context context,int themeResId);

For example:

Dialog customDialog = new Dialog (Mainactivity.this,R.style.dailogTheme);

Example of how to create a custom dialog

final Dialog customDialog = new Dialog(MainActivity.this);
        // the setContentView() method is used to set the custom layout for the dialog
        customDialog.setContentView(R.layout.custom_dailog_layout);
        // using window set the hight and width of custom dialog
        Window window = customDialog.getWindow();  window.setLayout(WindowManager.LayoutParams.MATCH_PARENT,      WindowManager.LayoutParams.WRAP_CONTENT);    window.setGravity(Gravity.CENTER);
        customDialog.show();// this show() method is used to show custom dialog

Now let’s see this in action by creating a new project.

1. Create a new project in Android Studio from File > New Project. When it prompts you to select the Empty activity, and proceed

Create a new project2. Create layout like below in activity_main.xml like this

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    android:orientation="vertical"
    tools:context="com.nimblechapps.custom_dailog.MainActivity">
   <Button
        android:id="@+id/btnShowDialog"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#26d60f"
        android:textColor="#FFFFFF"
        android:layout_alignParentBottom="true"
        android:text="Show Custom Dialog" />
   <Button
        android:id="@+id/btnAlertDialog"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#26d60f"
        android:textColor="#FFFFFF"
        android:layout_marginBottom="20dp"
        android:layout_above="@id/btnShowDialog"
        android:text="Show Alert Dialog" />
   <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
       <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical">
           <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="Name  :" />
           <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="Number  :" />
           <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="Gender  :" />
       </LinearLayout>
       <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="vertical">
           <TextView
                android:id="@+id/tvName"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="" />
           <TextView
                android:id="@+id/tvNumber"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="" />
           <TextView
                android:id="@+id/tvGender"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:text="" />
       </LinearLayout>
    </LinearLayout>
</RelativeLayout>

3. Create a layout resource file for custom Dialog

Create a layout resource file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
   <EditText
        android:id="@+id/edtUname"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:hint="Enter User Name"
        android:imeOptions="actionNext"
        android:inputType="text" />
   <EditText
        android:id="@+id/edtPhome"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:hint="Enter User Phone Number"
        android:imeOptions="actionNext"
        android:inputType="number"
        android:maxLength="10" />
   <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:padding="5dp"
        android:text="Select Geder"     
        android:textColor="#000" />
   <RadioGroup
        android:id="@+id/genderRadioGroup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp">
       <RadioButton
            android:id="@+id/maleRadioButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Male" />
       <RadioButton
            android:id="@+id/femaleRadioButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Female" />
   </RadioGroup>
   <Button
        android:id="@+id/btnOk"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginTop="20dp"
        android:background="#26d60f"
        android:text="OK"
        android:textColor="#FFFFFF"
        android:textStyle="bold" />
</LinearLayout>

4. Now create an Alert Dialog using Alert.Builder like this

Use setTitle() to set title of Alert Dialog

Use setMessage() to set message to Alert dialog

Use setPositiveButton() to set positive button of the dialog

Use setNegativeButton () to set negative button of the dialog

Use show() method to show Alert Dialog

Create an alert dialog using below code:

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); // create the object of alert dialog
        builder.setTitle(“TITLE"); // set the title of alert dialog using setTitle() method
        builder.setMessage("THIS IS ALERT DIALOG DEMO");//the msg with alert dialog using setMessage() method
        // now set the postive button with alert dialog and handle it result using setPositiveButton() method
        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this, "Ok Button Clicked", Toast.LENGTH_SHORT).show();
            }
        });
        // now set the negative button with alert dialog and handle it result using setNegativeButton() method
        builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toast.makeText(MainActivity.this, "Cancel Button Clicked", Toast.LENGTH_SHORT).show();
            }
        });
        builder.show(); // now show the alert dialog using show() method

5. Now create a custom dialog like this

Use setContentView() method to set custom layout to a custom dialog

Now programmatically set height and width of custom dialog using Window like this

Use show() method show custom Dialog

To access the controls of custom dialog bind all controls like this:

EditText) edtUname = (EditText) customDialog.findViewById(R.id.edtUname);

Now create a custom dialog like this

final Dialog customDialog = new Dialog(MainActivity.this);
        // the setContentView() method is used to set the custom layout for the dialog
        customDialog.setContentView(R.layout.custom_dailog_layout);
       final EditText edtUname, edtPhome;
        final RadioGroup genderRadioGroup;
        final RadioButton maleRadioButton, femaleRadioButton;
        final Button btnOk;
       gender = "";
       // using window set the hight and width of custom dialog
        Window window = customDialog.getWindow();
        window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, 
WindowManager.LayoutParams.WRAP_CONTENT);
        window.setGravity(Gravity.CENTER);
       // bind all controlss with custom dialog 
        btnOk = (Button) customDialog.findViewById(R.id.btnOk);
        genderRadioGroup = (RadioGroup) customDialog.findViewById(R.id.genderRadioGroup);
        maleRadioButton = (RadioButton) customDialog.findViewById(R.id.maleRadioButton);
        femaleRadioButton = (RadioButton) customDialog.findViewById(R.id.femaleRadioButton);
        edtUname = (EditText) customDialog.findViewById(R.id.edtUname);
        edtPhome = (EditText) customDialog.findViewById(R.id.edtPhome);
       genderRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, @IdRes int checkedId) {
               if (checkedId == R.id.maleRadioButton) {
                    gender = "Male";
                } else if (checkedId == R.id.femaleRadioButton) {
                    gender = "Female";
                }
            }
        });
        btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               if (edtPhome.getText().toString().trim().isEmpty()) {
                    edtPhome.setError("Please Enter Phone Number");
                    edtPhome.requestFocus();
                }
                if (edtPhome.getText().toString().trim().length() < 10) {
                    edtPhome.setError("Please Enter Valid Phone Number");
                    edtPhome.requestFocus();
                }
               if (edtUname.getText().toString().trim().isEmpty()) {
                    edtUname.setError("Please Entere User Name");
                    edtUname.requestFocus();
                }
               if (gender.isEmpty()) {
                    Toast.makeText(MainActivity.this, "Please Select Gender", Toast.LENGTH_SHORT).show();
                }
               if (!edtPhome.getText().toString().isEmpty() &&
                        !edtPhome.getText().toString().isEmpty() &&
                        edtPhome.getText().toString().trim().length() == 10 &&
                        !edtUname.getText().toString().isEmpty() &&
                        !gender.isEmpty()) {
                   tvName.setText(edtUname.getText().toString());
                    tvNumber.setText(edtPhome.getText().toString());
                    tvGender.setText(gender);
                    customDialog.dismiss();
                }
            }
        });
        customDialog.show();// this show() method is used to show custom dialog

Full code of main activity

package com.nimblechapps.custom_dailog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.support.annotation.IdRes;
import android.support.annotation.StringDef;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
   Button btnShowDialog, btnAlertDialog;
    TextView tvName, tvNumber, tvGender;
    public String gender = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       tvGender = (TextView) findViewById(R.id.tvGender);
        tvNumber = (TextView) findViewById(R.id.tvNumber);
        tvName = (TextView) findViewById(R.id.tvName);
      btnShowDialog = (Button) findViewById(R.id.btnShowDialog);
        btnAlertDialog = (Button) findViewById(R.id.btnAlertDialog);
       btnShowDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showCustomDialog();
            }
        });
       btnAlertDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showAlertDialog();
            }
        });
    }
   private void showAlertDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);// create the object of alert dailog
        builder.setTitle("TITLE");// set the title of alert dialog using setTitle() method
        builder.setMessage("THIS IS ALERT DIALOG DEMO");//the the msg with alert dialog using setMessage() method
        // now set the postive button with alert dialog and handle it result using setPositiveButton() method
        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this, "Ok Button Clicked", Toast.LENGTH_SHORT).show();
            }
        });
        // now set the negative button with alert dialog and handle it result using setNegativeButton() method
        builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toast.makeText(MainActivity.this, "Cancle Button Clicked", Toast.LENGTH_SHORT).show();
            }
        });
        builder.show();// now show the alert dialog using show() method
    }
    private void showCustomDialog() {
       final Dialog customDialog = new Dialog(MainActivity.this);
        // the setContentView() method is used to set the custom layout for the dialog
        customDialog.setContentView(R.layout.custom_dailog_layout);
       final EditText edtUname, edtPhome;
        final RadioGroup genderRadioGroup;
        final RadioButton maleRadioButton, femaleRadioButton;
        final Button btnOk;
       gender = "";
       // using window set the hight and width of custom dialog
        Window window = customDialog.getWindow();
        window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, 
WindowManager.LayoutParams.WRAP_CONTENT);
        window.setGravity(Gravity.CENTER);
       // bind all controlss with custom dialog
        btnOk = (Button) customDialog.findViewById(R.id.btnOk);
        genderRadioGroup = (RadioGroup) customDialog.findViewById(R.id.genderRadioGroup);
        maleRadioButton = (RadioButton) customDialog.findViewById(R.id.maleRadioButton);
        femaleRadioButton = (RadioButton) customDialog.findViewById(R.id.femaleRadioButton);
        edtUname = (EditText) customDialog.findViewById(R.id.edtUname);
        edtPhome = (EditText) customDialog.findViewById(R.id.edtPhome);
       genderRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, @IdRes int checkedId) {
               if (checkedId == R.id.maleRadioButton) {
                    gender = "Male";
                } else if (checkedId == R.id.femaleRadioButton) {
                    gender = "Female";
                }
            }
        });
        btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               if (edtPhome.getText().toString().trim().isEmpty()) {
                    edtPhome.setError("Please Enter Phone Number");
                    edtPhome.requestFocus();
                }
                if (edtPhome.getText().toString().trim().length() < 10) {
                    edtPhome.setError("Please Enter Valid Phone Number");
                    edtPhome.requestFocus();
                }
               if (edtUname.getText().toString().trim().isEmpty()) {
                    edtUname.setError("Please Entere User Name");
                    edtUname.requestFocus();
                }
               if (gender.isEmpty()) {
                    Toast.makeText(MainActivity.this, "Please Select Gender", Toast.LENGTH_SHORT).show();
                }
                if (!edtPhome.getText().toString().isEmpty() &&
                        !edtPhome.getText().toString().isEmpty() &&
                        edtPhome.getText().toString().trim().length() == 10 &&
                        !edtUname.getText().toString().isEmpty() &&
                        !gender.isEmpty()) {
                   tvName.setText(edtUname.getText().toString());
                    tvNumber.setText(edtPhome.getText().toString());
                    tvGender.setText(gender);
                    customDialog.dismiss();
                }
            }
        });
        customDialog.show();// this show() method is used to show custom dialog
    }
}

Conclusion

By using this tutorial now, you can create Alert Dialog and Custom Dialog. You can use modify as per your requirement dialog.

Nilesh Rathod
Nilesh is a mobile application developer. Android programming has been his passion since he compiled his first hello-world program. Solving real problems of Android developers is always interesting part for him. He just loves to help, share and learn knowledge through leading platforms like StackOverflow.