Easy Tutorial
❮ Quick Sort Javascript Autocomplete ❯

2.5.9 AlertDialog (Dialog Box) Detailed Explanation

Category Android Basic Tutorial

Introduction to This Section:

>

This section continues to introduce the third control for displaying prompt information, AlertDialog (Dialog Box), which is also the parent class of other Dialogs! Such as ProgressDialog, TimePickerDialog, etc., and the parent class of AlertDialog is: Dialog! In addition, unlike the Toast and Notification learned earlier, AlertDialog cannot be directly instantiated with new. If you open the source code of AlertDialog, you will find that the constructor is protected. If we want to create an AlertDialog, we need to use a static inner class in this class: public static class Builder, and then call the relevant methods in AlertDialog to customize it, and finally call the show() method to display our AlertDialog dialog box! Well, let's learn about the basic usage of AlertDialog and customize our AlertDialog! Official documentation: AlertDialog


1. Basic Usage Process

>

-Step 1: Create an AlertDialog.Builder object;

-Step 2: Call setIcon() to set the icon, setTitle() or setCustomTitle() to set the title;

-Step 3: Set the content of the dialog box: setMessage() and other methods to specify the displayed content;

-Step 4: Call setPositive/Negative/NeutralButton() to set: Confirm, Cancel, and Neutral buttons;

-Step 5: Call the create() method to create this object, and then call the show() method to display the dialog box;


2. Examples of Several Common Dialogs

Running Effect Picture:

Core Code:

MainActivity.java:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button btn_dialog_one;
    private Button btn_dialog_two;
    private Button btn_dialog_three;
    private Button btn_dialog_four;

    private Context mContext;
    private boolean[] checkItems;

    private AlertDialog alert = null;
    private AlertDialog.Builder builder = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = MainActivity.this;
        bindView();
    }

    private void bindView() {
        btn_dialog_one = (Button) findViewById(R.id.btn_dialog_one);
        btn_dialog_two = (Button) findViewById(R.id.btn_dialog_two);
        btn_dialog_three = (Button) findViewById(R.id.btn_dialog_three);
        btn_dialog_four = (Button) findViewById(R.id.btn_dialog_four);
        btn_dialog_one.setOnClickListener(this);
        btn_dialog_two.setOnClickListener(this);
        btn_dialog_three.setOnClickListener(this);
        btn_dialog_four.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //Normal dialog box
            case R.id.btn_dialog_one:
                alert = null;
                builder = new AlertDialog.Builder(mContext);
                alert = builder.setIcon(R.mipmap.ic_icon_fish)
                        .setTitle("System Prompt:")
                        .setMessage("This is the most common AlertDialog,\nwith three buttons, which are Cancel, Neutral, and Confirm")
                        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(mContext, "You clicked the Cancel button~", Toast.LENGTH_SHORT).show();
                            }
                        })
                        .setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(mContext, "You clicked the Confirm button~", Toast.LENGTH_SHORT).show();
                            }
                        })
                        .setNeutralButton("Neutral", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(mContext, "You clicked the Neutral button~", Toast.LENGTH_SHORT).show();
                            }
                        }).create();             // Create AlertDialog object
                alert.show();                    // Display the dialog box
                break;
            //Normal list dialog box
            case R.id.btn_dialog_two:
                final String[] lesson = new String[]{"Language", "Mathematics", "English", "Chemistry", "Biology", "Physics", "Physical Education"};
                alert = null;
                builder = new AlertDialog.Builder(mContext);
                alert = builder.setIcon(R.mipmap.ic_icon_fish)
                        .setTitle("Choose your favorite course")
                        .setItems(lesson, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(getApplicationContext(), "You chose " + lesson[which], Toast.LENGTH_SHORT).show();
                            }
                        }).create();
                alert.show();
                break;
            //Single-choice
public void onClick(DialogInterface dialog, int which) {
    Toast.makeText(getApplicationContext(), "You selected " + fruits[which], Toast.LENGTH_SHORT).show();
}
}).create();
alert.show();
break;
//Multi-choice list dialog
case R.id.btn_dialog_four:
final String[] menu = new String[]{"Boiled Tofu", "Radish Beef Brisket", "Soy Sauce Chicken", "Pepper Pork Tripe Chicken"};
//Define a boolean array to record the status of each list item
checkItems = new boolean[]{false, false, false, false};
alert = null;
builder = new AlertDialog.Builder(mContext);
alert = builder.setIcon(R.mipmap.ic_icon_fish)
.setMultiChoiceItems(menu, checkItems, new DialogInterface.OnMultiChoiceClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
        checkItems[which] = isChecked;
    }
})
.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        String result = "";
        for (int i = 0; i < checkItems.length; i++) {
            if (checkItems[i])
                result += menu[i] + " ";
        }
        Toast.makeText(getApplicationContext(), "You ordered: " + result, Toast.LENGTH_SHORT).show();
    }
})
.create();
alert.show();
break;
}

The layout consists of four simple buttons, which are not shown here. The usage is very simple ~ it's nothing more than creating a Builder object, 
making the relevant settings, then create() to generate an AlertDialog object, and finally calling the show() method to display the AlertDialog!
Additionally, you may have noticed that clicking outside the dialog box will make the dialog disappear. We can set **setCancelable(false)** for the builder to solve this problem!

---

## 3.Customize the AlertDialog displayed through Builder's setView()

>

We can customize a layout that is different from the system dialog, and then call setView() to load our layout onto the AlertDialog. Let's implement this effect:

**Running effect picture** :

**Key code** :

First, there are two different button selector drawable files:

**btn_selctor_exit.xml** :

```xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@mipmap/iv_icon_exit_pressed"/>
    <item android:drawable="@mipmap/iv_icon_exit_normal"/>
</selector>

btnselctorchoose.xml :

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@mipmap/bg_btn_pressed"/>
    <item android:drawable="@mipmap/bg_btn_normal"/>
</selector>

Next is the custom Dialog layout: viewdialogcustom.xml :

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

    <RelativeLayout
        android:id="@+id/titlelayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:background="#53CC66"
        android:padding="5dp">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:text="Prompt Information"
            android:textColor="#ffffff"
            android:textSize="18sp"
            android:textStyle="bold" />

        <Button
            android:id="@+id/btn_cancle"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_alignParentRight="true"
            android:background="@drawable/btn_selctor_exit" />

    </RelativeLayout>


    <LinearLayout
        android:id="@+id/ly_detail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/titlelayout"
        android:layout_centerInParent="true"
        android:orientation="vertical">

        &lt;TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="20dp"
            android:text="Customize AlertDialog through setView() method"
            android:textColor="#
```xml
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/ly_detail"
android:layout_marginTop="10dp"
android:orientation="horizontal">

<Button
    android:id="@+id/btn_blog"
    android:layout_width="match_parent"
    android:layout_height="40dp"
    android:layout_margin="5dp"
    android:layout_weight="1"
    android:background="@drawable/btn_selector_choose"
    android:text="Visit Blog"
    android:textColor="#ffffff"
    android:textSize="20sp" />

<Button
    android:id="@+id/btn_close"
    android:layout_width="match_parent"
    android:layout_height="40dp"
    android:layout_margin="5dp"
    android:layout_weight="1"
    android:background="@drawable/btn_selector_choose"
    android:text="Close"
    android:textColor="#ffffff"
    android:textSize="20sp" />

</LinearLayout>

</RelativeLayout>
public class MainActivity extends AppCompatActivity {

    private Button btn_show;
    private View view_custom;
    private Context mContext;
    private AlertDialog alert = null;
    private AlertDialog.Builder builder = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = MainActivity.this;
        btn_show = (Button) findViewById(R.id.btn_show);

        // Initialize Builder
        builder = new AlertDialog.Builder(mContext);

        // Load the custom View and set it up
        final LayoutInflater inflater = MainActivity.this.getLayoutInflater();
        view_custom = inflater.inflate(R.layout.view_dialog_custom, null, false);
        builder.setView(view_custom);
        builder.setCancelable(false);
        alert = builder.create();

        view_custom.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alert.dismiss();
            }
        });

        view_custom.findViewById(R.id.btn_blog).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(), "Visit Blog", Toast.LENGTH_SHORT).show();
                Uri uri = Uri.parse("http://blog.csdn.net/coder_pig");
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
                alert.dismiss();
            }
        });

        view_custom.findViewById(R.id.btn_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(), "Dialog has been closed~", Toast.LENGTH_SHORT).show();
                alert.dismiss();
            }
        });

        btn_show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alert.show();
            }
        });
    }
}

4. Example Code Download

AlertDialogDemo.zip

AlertDialogDemo1.zip


Summary of This Section:

Well, in this section, we introduced the basic usage of AlertDialog, wrote several examples of calling AlertDialog, and finally customized our AlertDialog with the setView method! Are you still not satisfied? But this is not a real custom control. We will put custom controls into the advanced series, and there will be a special topic to discuss with you about custom controls later. Please look forward to it. That's all, thank you~

❮ Quick Sort Javascript Autocomplete ❯