The Dialog of the Android

  • Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

A list,

The function of the dialog box is to prompt some information to the user, so that the user can perform the next operation, or remind the user that the operation is irreversible.

However, the dialog box itself is not complex, complex is used in combination with other controls.

Several common dialogs are described below.

Properties and methods

The Dialog box provided by the Android system is Dialog, which does not realize specific types of Dialog boxes, such as radio, multiple selection, list and other Dialog boxes, but only provides a framework and specifications. System for developers to provide a multifunctional dialog class AlertDialog, encapsulating a variety of dialog styles, we only need to complete the content to display and monitor.

Most dialogs are instance objects that use the system-wrapped dialogs AlertDialog. An AlertDialog does not provide an external constructor, that is, an AlertDialog constructor cannot be directly used to produce an AlertDialog. Because all of the constructors of an AlertDialog are protected. So to get an AlertDialog object, the system provides a static inner class Builder for us to use to create an AlertDialog object.

The Builder object sets the properties of the dialog box

	.setTitle() // Set the title
	.setIcon ()// Set the icon
       .setMessage ()// Set the content to display
       .setItems// Sets the list of items to display in the dialog box
       .setView// Set custom dialog box styles
       .setPositiveButton ()// Set the ok button
       .setNegativeButton ()// Set the cancel button
       .setNeutralButton ()// Set the neutral button
       .setSingleChoiceItems/ / radio buttons
       .setMultiChoiceItems/ / check box
Copy the code

The use of dialogs

The use of dialog box in Android is everywhere, the use is very extensive, a good dialog box can improve the user’s sense of use. This is very important in Android development.

This section describes the use of these common dialog boxes.

Use steps:

  1. Create an AlertDialog.Builder instance object.
  2. Set the properties of the dialog box using the Builder object.
  3. Create the AlertDialog dialog by calling the Create () method of the Builder object
  4. Call the Show () method of the AlertDialog to display the dialog
  5. Call the Dimiss () method of the AlertDialog to destroy the dialog box.

1, ordinary dialog box

When we want to prompt the user some information, as well as let the user make some choices, can be a simple dialog box.

As shown:

Java core code:

AlertDialog dialog=new AlertDialog.Builder(this)
                        .setIcon(R.drawable.hmbb)// Set the icon
                        .setTitle("I'm a normal dialog box.")// Set the title
                        .setMessage("I am the content")// Set the content to display
                        .setNegativeButton("Cancel".new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                Toast.makeText(MainActivity.this."Hit the cancel button.", Toast.LENGTH_SHORT).show();
                                dialogInterface.dismiss();// Destroy dialog box
                            }
                        })
                    .setNeutralButton("Third Party Button".new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            Toast.makeText(MainActivity.this."I'm the third button", Toast.LENGTH_SHORT).show();
                        }
                        })
                        .setPositiveButton("Sure".new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(MainActivity.this."Clicked the OK button.", Toast.LENGTH_SHORT).show();
                                dialog.dismiss();// Destroy dialog box
                            }
                        }).create();// The create () method creates the dialog
                dialog.show();// Displays a dialog box
Copy the code

2. List dialog box

As shown:

Java core code:

final String hobby[] = {"Eat"."Sleep"."Knock code"."Watch TV"."Play video games"};
                AlertDialog dialog1=new AlertDialog.Builder(this)
                        .setIcon(R.drawable.hmbb)
                        .setTitle("Please choose your favorite hobby.")
                        .setItems(hobby, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                Toast.makeText(MainActivity.this, hobby[i], Toast.LENGTH_SHORT).show();
                            }
                        })
                        .setNegativeButton("Cancel".new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .setPositiveButton("Sure".new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).create();
                dialog1.show();
Copy the code

3. Radio dialog box

The effect is as follows:

Core Java code:

             final String[] gaame = new String[]{Honor of Kings."LOL"."QQ speed"."Dungeons".Onmyoji};
                AlertDialog dialog2=new AlertDialog.Builder(this)
                        .setIcon(R.drawable.game)
                        .setTitle("Please choose your favorite game.")
                        // First argument: set the radio resource; Second parameter: sets which items are selected by default
                        .setSingleChoiceItems(gaame, 0.new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int i) {
                                Toast.makeText(MainActivity.this, gaame[i], Toast.LENGTH_SHORT).show();
                            }
                        })
                        .setNegativeButton("Cancel".new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .setPositiveButton("Sure".new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).create();
                dialog2.show();
Copy the code

4. Multiple Selection dialog box

The effect is as follows:

Core Java code:

    final String items[] = {"Basketball"."Football"."Volleyball"."Table tennis"."Badminton"."Running"};
                final boolean checkedItems[] = {true.false.false.false.true.true};
                AlertDialog dialog3 = new AlertDialog.Builder(this)
                        .setIcon(R.drawable.hmbb)// Set the caption image
                        .setTitle("Choose an exercise you love.")// Set the title of the dialog box
                        // First argument: set the radio resource; Second parameter: sets which items are selected by default
                        .setMultiChoiceItems(items, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int i, boolean isChecked) {
                                checkedItems[i] = isChecked;
                            }
                        })
                        .setNegativeButton("Cancel".new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .setPositiveButton("Sure".new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                for (int i = 0; i < checkedItems.length; i++) {
                                    if (checkedItems[i]) {
                                        Toast.makeText(MainActivity.this."Selected" + i, Toast.LENGTH_SHORT).show();
                                    }
                                }
                                dialog.dismiss();
                            }

                        }).create();
                dialog3.show();
Copy the code

5. Progress bar dialog box

ProgressDialog is also a descendant of Dialog, but extends the ability to buffer load prompts.

The effect is as follows:

Java core code:

// Instantiate a ProgressDialog progress bar dialog object
final ProgressDialog progressDialog=new ProgressDialog(this);
  // Set the progress bar to horizontal
  progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                progressDialog.setMessage("Loading");
                progressDialog.setMax(100);
                final Timer timer=new Timer();
                        timer.schedule(new TimerTask() {
                    int startprogress=0;
                    @Override
                    public void run(a) {
                        startprogress+=new Random().nextInt(10);
                        progressDialog.setProgress(startprogress);
                        if (startprogress>100) timer.cancel(); }},0.1000);

            progressDialog.show();
            break;
Copy the code

If you want to implement a rotating progress bar

Java core code:

    ProgressDialog progressDialog1 = new ProgressDialog(this);
                progressDialog1.setMessage("Loading");
                progressDialog1.show();
Copy the code

6. Date Selection dialog box

The effect is as follows:

Java core code:

Calendar data=Calendar.getInstance();
                DatePickerDialog dpd=new DatePickerDialog(this.new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int day) {
                        String str;
                        str = String.valueOf(year) + "-" + String.valueOf(month) + "-" + String.valueOf(day);
                        Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG).show();
                    }

                },data.get(Calendar.YEAR),data.get(Calendar.MONTH),data.get(Calendar.DAY_OF_MONTH));
                dpd.show();
Copy the code

7. Time selection dialog box

The effect is as follows:

Java core code:

Calendar calendar=Calendar.getInstance();
                new TimePickerDialog(this.new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

                    }
                },
                    calendar.get(Calendar.HOUR_OF_DAY),
                    calendar.get(Calendar.MINUTE),
                    true
                ).show();
Copy the code

8. Customize dialog box

The custom dialog basically uses this.setView(View) method to load a layout that we’ve customized.

The effect is as follows:

First we need to remove the default style of the system Dialog to avoid affecting our style layout

In res->values->style.xml, add our style to remove the system dialog box

 <! -- Dialog box style -->
    <style name="NormalDialogStyle">
        <! -- Dialog background -->
        <item name="android:windowBackground">@android:color/transparent</item>
        <! - frame - >
        <item name="android:windowFrame">@null</item>
        <! -- No title -->
        <item name="android:windowNoTitle">true</item>
        <! -- Whether to appear on the Activity -->
        <item name="android:windowIsFloating">true</item>
        <! -- Transparent background -->
        <item name="android:windowIsTranslucent">false</item>
        <! -- Whether there is coverage -->
        <item name="android:windowContentOverlay">@null</item>
        <! -- Background darkens -->
        <item name="android:backgroundDimEnabled">true</item>
    </style>
Copy the code

Write custom layout code for the div_dialog.xml dialog box


      
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#3CC4C4"
        android:text="Click login" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:background="#ddd" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#D1FAF2"
        android:text="Personal Center" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:background="#ddd" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#3CC4C4"
        android:text="My Collection" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:background="#ddd" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#D1FAF2"
        android:text="My Collection" />


    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:background="#2BD5D5"
        android:text="Cancel" />

    <View
        android:layout_width="match_parent"
        android:layout_height="15dp" />
</LinearLayout>
Copy the code

Java core code:

 // Instantiate the Dialog object and apply NormalDialogStyle to remove the system style
                Dialog dialog4 = new Dialog(this,R.style.NormalDialogStyle);
                View view = View.inflate(this, R.layout.div_dialog, null);
                dialog4.setContentView(view);// Set a view for the dialog
                dialog4.setCanceledOnTouchOutside(true);// You can exit by clicking somewhere outside the window
                Window dialogWindow = dialog4.getWindow();// Get the Dialog window
                // Instantiate the window layout object
                WindowManager.LayoutParams lp = dialogWindow.getAttributes();
                lp.width =WindowManager.LayoutParams.MATCH_PARENT;// The width is full
                lp.height = WindowManager.LayoutParams.WRAP_CONTENT;// Highly adaptive
                lp.gravity = Gravity.BOTTOM;// The window is anchored at the bottom center
                dialogWindow.setAttributes(lp);
                dialog4.show();
Copy the code

Common dialog boxes are introduced almost. ゚, remember. ◕ ‿ ◕.) ノ ゚. :. + ゚

Have a ‘like’ and go ٩(danjun ´0 ‘danjun) p. To Mr!