Android Custom Alert Dialog

Filed Under: Android

In this tutorial, we’ll be discussing and implementing Custom Alert Dialogs in our Android Application.
We’d discussed Android Alert Dialogs already here.

Alert Dialogs

Alert Dialogs by default are used to create dialogs with text messages and button actions.
Following are the setter methods that we’d already discussed in the previous tutorial.

  • setTitle
  • setMessage
  • setPositiveButton
  • setNegativeButton
  • setNeutralButton
  • setPositiveButtonIcon/setNegativeButtonIcon/setNeutralButtonIcon
  • setCancelable
  • setIcon
  • setOnDismissListener
  • setItems – shows an array of items in the form of a list inside the alert dialog
  • setMultiChoiceItems – Sets a list of items to choose from inside the alert dialog
  • setView – Used to set a custom layout view inside the alert dialog.
  • show()
  • setShowListener() – This is triggered when the alert dialog is displayed on the screen. We can do any dynamic changes in here
A ProgressDialog is an AlertDialog with the ProgressBar widget.

In the following section we’ll create different types of custom alert dialog:

  • With List of Items
  • With EditText
  • With ImageView
  • With SeekBar
  • With RatingBar

Project Structure

android custom alert dialog project structure

Code

The code for the activity_main.xml layout file is given below:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btnSimpleAlert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="simpleAlert"
        android:text="SIMPLE ALERT DIALOG"/>

    <Button
        android:id="@+id/btnAlertWithItems"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="withItems"
        android:text="WITH ITEMS"/>

    <Button
        android:id="@+id/btnAlertWithMultiChoiceItems"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="withMultiChoiceItems"
        android:text="WITH MULTI CHOICE ITEMS"/>

    <Button
        android:id="@+id/btnAlertWithEditText"
        android:layout_width="wrap_content"
        android:onClick="withEditText"
        android:layout_height="wrap_content"
        android:text="WITH EDIT TEXT"/>

    <Button
        android:id="@+id/btnAlertWithImageView"
        android:layout_width="wrap_content"
        android:onClick="withImageView"
        android:layout_height="wrap_content"
        android:text="WITH IMAGE VIEW"/>

    <Button
        android:id="@+id/btnAlertWithSeekBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="withSeekBar"
        android:text="WITH SEEK BAR"/>

    <Button
        android:id="@+id/btnAlertWithRatingBar"
        android:layout_width="wrap_content"
        android:onClick="withRatingBar"
        android:layout_height="wrap_content"
        android:text="WITH RATING BAR"/>

</LinearLayout>

Each of the Buttons would create an AlertDialog. We’ve set the onClick method for each of them which would be defined in the MainActivity.java class.

Simple Alert Dialog

Add the following method(s) to your MainActivity.java:


public void simpleAlert(View view) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Simple Alert");
        builder.setMessage("We have a message");
        builder.setPositiveButton("OK",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(getApplicationContext(),
                                "OK was clicked",
                                Toast.LENGTH_SHORT).show();
                    }
                });
        builder.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(getApplicationContext(),
                        android.R.string.no, Toast.LENGTH_SHORT).show();
            }
        });
        builder.setCancelable(false);
        builder.show();
    }

This is the simplest form of AlertDialog. Let’s get onto the more interesting ones.

AlertDialog.Builder is used to build the AlertDialog.

To display the AlertDialog we can alternatively use the following code as well:


AlertDialog alertDialog = builder.create();
alertDialog.show();

AlertDialog Showing List Of Items


public void withItems(View view) {

        final String[] items = {"Apple", "Banana", "Orange", "Grapes"};
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("List of Items")

                .setItems(items, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(getApplicationContext(), items[which] + " is clicked", Toast.LENGTH_SHORT).show();
                    }
                });

        builder.setPositiveButton("OK", null);
        builder.setNegativeButton("CANCEL", null);
        builder.setNeutralButton("NEUTRAL", null);
        builder.setPositiveButtonIcon(getResources().getDrawable(android.R.drawable.ic_menu_call, getTheme()));
        builder.setIcon(getResources().getDrawable(R.drawable.jd, getTheme()));

        AlertDialog alertDialog = builder.create();

        alertDialog.show();

        Button button = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
        button.setBackgroundColor(Color.BLACK);
        button.setPadding(0, 0, 20, 0);
        button.setTextColor(Color.WHITE);
    }

In the setItems method we pass the array of strings we want to display.
which argument contains the index of the list item that is clicked.

We can customize the Button texts and style by retrieving the Button instances over the alertDialog instance and setting the text color etc.

By default, the color of the Buttons is set from the colorAccent value defined in the styles.xml

AlertDialog With Multiple Selection List


public void withMultiChoiceItems(View view) {
        final String[] items = {"Apple", "Banana", "Orange", "Grapes"};
        final ArrayList<Integer> selectedList = new ArrayList<>();
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setTitle("This is list choice dialog box");
        builder.setMultiChoiceItems(items, null,
                new DialogInterface.OnMultiChoiceClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                        if (isChecked) {
                            selectedList.add(which);
                        } else if (selectedList.contains(which)) {
                            selectedList.remove(which);
                        }
                    }
                });

        builder.setPositiveButton("DONE", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                ArrayList<String> selectedStrings = new ArrayList<>();

                for (int j = 0; j < selectedList.size(); j++) {
                    selectedStrings.add(items[selectedList.get(j)]);
                }

                Toast.makeText(getApplicationContext(), "Items selected are: " + Arrays.toString(selectedStrings.toArray()), Toast.LENGTH_SHORT).show();

             
            }
        });

        builder.show();

    }

This is a better version of the simple list of items that we saw earlier.
Each of the items in the list has a CheckBoxbeside it. The isChecked boolean value returns the checkBox current state.

Once the Button is clicked, we show the list of items that were selected by converting the ArrayList populated of the selectedItems into an Array.

AlertDialog With EditText

Using the setView property we can set a custom view from the layout or do that programmatically as well.
In the below function we've done it programmatically.


public void withEditText(View view) {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("With Edit Text");

        final EditText input = new EditText(MainActivity.this);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        input.setLayoutParams(lp);
        builder.setView(input);
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toast.makeText(getApplicationContext(), "Text entered is " + input.getText().toString(), Toast.LENGTH_SHORT).show();
            }
        });
        builder.show();
    }

Alert Dialog With ImageView

Here we'll inflate a custom layout inside our setView method.
Following is the layout that'll be shown inside the AlertDialog:

alert_dialog_with_imageview.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="350dp"
        android:scaleType="centerCrop"
        android:adjustViewBounds="true"
        android:src="@drawable/sample"/>

</LinearLayout>

Add the following function inside your MainActivity.java class:


public void withImageView(View view) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater inflater = getLayoutInflater();
        View dialogLayout = inflater.inflate(R.layout.alert_dialog_with_imageview, null);
        builder.setPositiveButton("OK", null);
        builder.setView(dialogLayout);
        builder.show();
    }

Alert Dialog With Seekbar


public void withSeekBar(View view) {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("With SeekBar");
        final SeekBar seekBar = new SeekBar(MainActivity.this);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        seekBar.setLayoutParams(lp);
        builder.setView(seekBar);
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toast.makeText(getApplicationContext(), "Progress is " + seekBar.getProgress(), Toast.LENGTH_SHORT).show();
            }
        });
        builder.show();

    }

On clicking the Button we show the progress value of the SeekBar.

Alert Dialog With Rating Bar


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RatingBar
        android:id="@+id/ratingBar"
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:numStars="5"
        android:stepSize="0.5" />

</LinearLayout>

public void withRatingBar(View view) {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater inflater = getLayoutInflater();
        builder.setTitle("With RatingBar");
        View dialogLayout = inflater.inflate(R.layout.alert_dialog_with_ratingbar, null);
        final RatingBar ratingBar = dialogLayout.findViewById(R.id.ratingBar);
        builder.setView(dialogLayout);
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toast.makeText(getApplicationContext(), "Rating is " + ratingBar.getRating(), Toast.LENGTH_SHORT).show();
            }
        });
        builder.show();
    }

Once you've added all the above methods inside the MainActivity.java class let's build and run our application. Following is the output of the above application in action.

android custom alert dialog demo output

This brings an end to this tutorial. You can download the project from the link below:

Comments

  1. Aamil Silawat says:

    Your coding is Very Clean well played 😀

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages