[Android] Comprehensive list of commonly used dialog boxes (1) Android Dialog

How many types of dialog boxes are there in Android? There are many good-looking dialog boxes in Android, such as Android, material, qmui, xui, kongzue and other series of dialog boxes, but the blogger only intends to explain the Android and material series of dialog boxes. There is no need to talk too much. I really want to be like an adult. dialog box, just take some time to customize it.

Android common dialog box series of articles

[Android] Comprehensive list of commonly used dialog boxes (1) Android Dialog

【Android】Comprehensive list of commonly used dialog boxes (2) Material Dialog

[Android] Comprehensive list of commonly used dialog boxes (3) Three ways to customize Dialog (Theme, PopupWindow, Dialog)

AlertDialogSeries

The implementation methods of the AlertDialog series of dialog boxes are all AlertDialogrelated to classes. It can be said that one class can implement multiple types of dialog boxes.

Prompt dialog box

Insert image description here
Implementation code:

AlertDialog.Builder(this)
            .setTitle("消息对话框")
            .setMessage("这是一个消息对话框!")
            .setNegativeButton("不像") {
    
     dialog: DialogInterface?, which: Int -> showMessage("真不像?") }
            .setPositiveButton("明明就是") {
    
     dialog: DialogInterface?, which: Int -> showMessage("明明就是") }
            .show()
use methods Describe
setTitle(CharSequence title) Sets the title displayed in the dialog box
setMessage(CharSequence message) Set the message to be displayed
setNegativeButton(CharSequence text, final OnClickListener listener) Sets a listener to be called when the dialog's negative button is pressed
setPositiveButton(CharSequence text, final OnClickListener listener) Sets a listener to be called when the dialog's OK button is pressed

Left and right button dialog

Insert image description here
Implementation code:

AlertDialog.Builder(this)
            .setMessage("左右按钮对话框!")
            .setNeutralButton("左") {
    
     dialog: DialogInterface?, which: Int -> showMessage("左") }
            .setPositiveButton("右") {
    
     dialog: DialogInterface?, which: Int -> showMessage("右") }.show()
use methods Describe
setMessage(CharSequence message) Set the message to be displayed
setNeutralButton(CharSequence text, final OnClickListener listener) Sets a listener to be called when the dialog's neutral button is pressed
setPositiveButton(CharSequence text, final OnClickListener listener) Sets a listener to be called when the dialog's positive button is pressed

List dialog

Insert image description here
Implementation code:

AlertDialog.Builder(this)
            .setItems(items) {
    
     dialog: DialogInterface?, which: Int -> showMessage("点击了列表对话框的 " + items[which]) }
            .show()
use methods Describe
setItems(CharSequence[] items, final OnClickListener listener) Sets the list of items to be displayed in the dialog as content, you will be notified of the selected items via the provided listener

radio selection dialog

Insert image description here
Implementation code:

AlertDialog.Builder(this)
            .setTitle("单选对话框")
            .setSingleChoiceItems(items,0) {
    
     dialog: DialogInterface?, which: Int -> 
            	singleSelectResult = items[which] 
            }
            .setPositiveButton("确定") {
    
     dialog: DialogInterface?, which: Int ->
                showMessage(singleSelectResult)
            }
            .show()
use methods Describe
setTitle(CharSequence title) Set the title displayed in the Dialog
setSingleChoiceItems(CharSequence[] items, int checkedItem, final OnClickListener listener) Set a list of items to be displayed in the dialog as content, you will be notified of the selected items via the provided listener. The list will display a check mark to the right of the selected item's text. Clicking an item in the list does not close the dialog box. Clicking the button will close the dialog box.
setPositiveButton(CharSequence text, final OnClickListener listener) Sets a listener to be called when the dialog's positive button is pressed

Multiple selection dialog

Insert image description here
Implementation code:

val bool = booleanArrayOf(false, false, false, false)
        AlertDialog.Builder(this)
            .setTitle("多选对话框")
            .setMultiChoiceItems(items,bool) {
    
     dialog: DialogInterface?, which: Int, isChecked: Boolean -> }
            .setPositiveButton("确定") {
    
     dialog: DialogInterface?, which: Int ->
                var result = "选中了"
                for (i in bool.indices) {
    
    
                    if (bool[i]) {
    
    
                        result += items[i]
                    }
                }
                showMessage(result)
            }.show()
use methods Describe
setTitle(CharSequence title) Set the title displayed in the Dialog
setMultiChoiceItems(CharSequence[] items, boolean[] checkedItems, final OnMultiChoiceClickListener listener) Set a list of items to be displayed in the dialog as content, you will be notified of the selected items via the provided listener. The list will display a check mark to the right of the text for each selected item. Clicking an item in the list does not close the dialog box. Clicking the button will close the dialog box.
setPositiveButton(CharSequence text, final OnClickListener listener) Sets a listener to be called when the dialog's positive button is pressed

Ring progress bar dialog box (customized)

The ring progress bar dialog box is the same as the horizontal progress bar dialog box. It can be displayed directly in lower versions of Android systems ProgressDialog(refer to the progress bar dialog box below). Just setProgressStyle(int style)change the parameters to ProgressDialog.STYLE_SPINNER.
If you need to customize the Android dialog box, the steps are similar to the horizontal progress bar dialog box, except that the layout is different, as follows:

1. xml layout

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

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"/>

    <TextView
        android:id="@+id/percentage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:text="正在下载..."
        android:textSize="16dp"
        android:textStyle="bold"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"/>
</LinearLayout>

2. Setting in Java

AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
View inflate = LayoutInflater.from(this).inflate(R.layout.progress_bar2, null);
// 设置一直滚动的效果
for (int i = 0; i <= 100 ; i++) {
    
    
    if (i == 0){
    
    
        i = 100;
    }
    ((ProgressBar)inflate.findViewById(R.id.progressBar)).setProgress(i);
}
alertDialog.setView(inflate);
AlertDialog dialog = alertDialog.create();
dialog.show();
// 设置对话框宽高,要先show()再设置才回生效
Window window = dialog.getWindow();
WindowManager.LayoutParams attributes = window.getAttributes();
attributes.width = 700;
attributes.height = WindowManager.LayoutParams.WRAP_CONTENT;
attributes.gravity = Gravity.CENTER;
window.setAttributes(attributes);

The effect is as follows:
Insert image description here

Dialog with radius (custom)

Everyone should encounter such a problem when developing a dialog box with a radius. The radius is set but the effect is not displayed. I have tried this situation two or three times, and each time I rely on the answers of netizens to help me get through it. For this disaster, make a radius dialog box to record it. If you encounter this kind of problem again, you don't need to run around to find the reason.
1. Create a dialog_radius.xml layout file in layout as the layout file of the dialog box.

<?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:layout_gravity="center"
    android:background="@drawable/background_radius">

    <TextView
        android:layout_width="333dp"
        android:layout_height="320dp"
        android:gravity="center"
        android:text="有半径的对话框"
        android:textSize="25sp" />
</LinearLayout>

2. Create a background_radius.xml file in the drawable folder as the background of the dialog box.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:radius="20dp"/>
    <solid android:color="@color/white"/>
</shape>

3. After setting the parameters in the code, show()a dialog box will appear.

// 创建一个AlertDialog并设置View布局文件
val dialog: AlertDialog = AlertDialog.Builder(this).setView(R.layout.dialog_radius).create()
dialog.show()

But not all the work has been completed at this time. The dialog box that runs at this time must be a dialog box without a radius, which means that the radius we set has not taken effect. The reason is AlertDialogthat it has its own background, which needs to AlertDialogbe hidden in order to display the set radius dialog box normally.

// 设置对话框显示的位置
dialog.window!!.setGravity(Gravity.CENTER);
// 将背景设置为透明
dialog.window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT));

Modifying the width and height in the dialog_radius.xml layout will not change the width and height of the dialog box. The only way to set the width is to use the following method to set the width match_parent. wrap_contentThe height can only be set to the specified dp, and the width and height cannot be set by the parent layout. The height will only increase as the height of the sublayout increases. Of course, the height of the dialog box can also be set in the following way.

// 在xml设置的宽度、高度不起作用时,可使用如下方法设置宽高
// setLayout(int width, int height)设置的宽高默认为px单位,如需适配其它屏幕需要转换
dialog.window!!.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

The effect is as follows:
Insert image description here

Other common properties of AlertDialog

use methods Describe
setIcon(Drawable icon) Set Drawable to use in title
setCancelable(boolean cancelable) Set whether the dialog box can be canceled
setCustomTitle(View customTitleView) Set title using custom view customTitleView
setAdapter(ListAdapter adapter, DialogInterface.OnClickListener listener) Sets the list of items provided by the given ListAdapter as content is displayed in the dialog, you will be notified of the selected items through the provided listener

date time series

The date and time series dialog box uses two classes, namely, and TimePickerDialog. DatePickerDialogThese two dialog boxes do not have many styles. They only do their own professional things. For example TimePickerDialog, you can only make a time selection dialog box and cannot do similar AlertDialogthings . Multiple styles to one class. At the same time, TimePickerDialogthe DatePickerDialogparent classes of and are both AlertDialog, which makes AlertDialogthe public methods of both dialog boxes available.

time picker

TimePickerDialog

TimePickerDialogThere are not many methods in the class. Just write the constructor method + directly show()and the effect will come out.

TimePickerDialog(this,{
    
     timePicker: TimePicker?, hourOfDay: Int, minute: Int -> 
		show("选中了" + hourOfDay + "时" + minute + "分") 
	},0,0,true).show()

Insert image description here

TimePickerDialogProperty
Public constructors Describe
TimePickerDialog(Context context, TimePickerDialog.OnTimeSetListener listener, int hourOfDay, int minute, boolean is24HourView) Create a new time picker dialog
TimePickerDialog(Context context, int themeResId, TimePickerDialog.OnTimeSetListener listener, int hourOfDay, int minute, boolean is24HourView) Creates a new time picker dialog with the specified theme
Public methods Describe
onClick(DialogInterface dialog, int which) This method is called when a button in the dialog is clicked
onRestoreInstanceState(Bundle savedInstanceState) Restore the state of a dialog box from a previously saved package
onSaveInstanceState() Save the dialog's state to a package
updateTime(int hourOfDay, int minuteOfHour) Set current time
show() Launch a dialog box and display it on the screen

date picker

DatePickerDialog

DatePickerDialogJust TimePickerDialoglike a class, write the constructor + directly show()and the effect will come out.

DatePickerDialog(this,{
    
     datePicker: DatePicker?, year: Int, month: Int, dayOfMonth: Int -> 
		show("选中了" + year + "年" + month + "月" + dayOfMonth + "日") 
	},2022,5,25).show()

Insert image description here

DatePickerDialogProperties
Public constructors Describe
DatePickerDialog(context: Context) Creates a new datepicker dialog for the current date using the parent context's default datepicker dialog theme
DatePickerDialog(context: Context, themeResId: Int) Create a new date picker dialog for the current date
DatePickerDialog(context: Context, listener: DatePickerDialog.OnDateSetListener?, year: Int, month: Int, dayOfMonth: Int) Creates a new datepicker dialog for the specified date using the parent context's default datepicker dialog theme
DatePickerDialog(context: Context, themeResId: Int, listener: DatePickerDialog.OnDateSetListener?, year: Int, monthOfYear: Int, dayOfMonth: Int) Creates a new date picker dialog for the specified date
Public methods Describe
onClick(dialog: DialogInterface, which: Int) This method is called when a button in the dialog is clicked
onDateChanged(view: DatePicker, year: Int, month: Int, dayOfMonth: Int) Request a date change
setOnDateSetListener(listener: DatePickerDialog.OnDateSetListener?) Set up a listener that is called when the user sets a date
updateDate(year: Int, month: Int, dayOfMonth: Int) Set current date

Progress bar series (ProgressDialog)

The progress bar dialog box can be displayed directly on lower versions of Android systems ProgressDialog, which is simple and fast.

val progressDialog = ProgressDialog(this)
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL)
progressDialog.setTitle("正在下载...")
progressDialog.progress = 50
progressDialog.show()

Unfortunately, this class has been deprecated in Android 8 and above.

Insert image description here

To achieve similar effects, we can only customize it.
ProgressDialogThe direct parent class of the class is AlertDialog, which AlertDialogshould be the easiest way to implement a horizontal progress bar dialog box. Proceed as follows:

ProgressBar1. Define an xml layout and use the horizontal progress bar in the layout ProgressDialog.

<androidx.constraintlayout.widget.ConstraintLayout 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:paddingBottom="10dp"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="25dp"
        android:layout_marginRight="25dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"/>

    <TextView
        android:id="@+id/percentage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@id/progressBar"
        app:layout_constraintRight_toRightOf="parent"
        android:text="0%"
        android:layout_marginRight="25dp"/>

</androidx.constraintlayout.widget.ConstraintLayout>

2. Use AlertDialog.Builderthe setView(View view)method to insert the prepared xml into AlertDialog.Builderit.

val alertDialog = AlertDialog.Builder(this)
alertDialog.setTitle("水平进度条对话框")
val inflate = LayoutInflater.from(this).inflate(R.layout.progress_bar, null)
(inflate.findViewById(R.id.progressBar) as ProgressBar).progress = 50
(inflate.findViewById(R.id.percentage) as TextView).text = "50%"
alertDialog.setView(inflate)
alertDialog.show()

The effect is as follows:

2.png


Click to download source code

Reference documentation: Android developers

Guess you like

Origin blog.csdn.net/baidu_41616022/article/details/125182197