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

Preface

In the previous article, this series of articles will explain Android dialog and Material dialog. Why should we talk about Material? Developers who have developed Flutter may understand that the Material Design framework is also used by Flutter, and the introduction on its official website says this: Material is a design system created by Google to help teams develop solutions for Android, iOS, and Flutter. and the web to build high-quality digital experiences. As you can imagine, Material Design is widely used. This is why the blogger brought Material Dialog into this series of articles.

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)

Material DesignPlease make sure you have imported the following dependencies when using

implementation 'com.google.android.material:material:1.5.0'

MaterialAlertDialogBuilder series

The Material Dialog series uses MaterialAlertDialogBuilderclass implementation, and its parent class inherits from AlertDiolag.Builder, which is AlertDialog.Builderan extension of
, which means that AlertDialog.BuiderMaterial Dialog can also use the properties it has.

It should be noted that MaterialAlertDialogBuilderin the source code, MaterialAlertDialogBuilderthe class will modify the current Dialog style according to the style of the current theme. To show the real style of Material Dialog, you need to android:thememodify the AndroidManifest.xml file to one of the following themes to take effect.

Theme Describe
Theme.Material3.Light Bright, bright color theme is mainly white
Theme.Material3.Light.NoActionBar Bright, bright color theme is mainly white, and there is no ActionBar
Theme.Material3.Dark Dark, mainly dark themes
Theme.Material3.Dark.NoActionBar Dark, mainly dark themes, and no ActionBar
Theme.Material3.DayNight sameTheme.Material3.Light
Theme.Material3.DayNight.NoActionBar sameTheme.Material3.Light.NoActionBar

Next, write the code to show everyone what the Material Dialog looks like.

Prompt dialog box

Insert image description here

Implementation code:

MaterialAlertDialogBuilder(this)
		    .setTitle("消息对话框")
		    .setMessage("这是一个消息对话框!")
		    .setNegativeButton("不像") {
    
     dialog, which ->
		        showMessage(view,"真不像?")
		    }
		    .setPositiveButton("明明就是") {
    
     dialog: DialogInterface?, which: Int ->
		        showMessage(view,"明明就是")
		    }
		    .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:

MaterialAlertDialogBuilder(this)
            .setMessage("左右按钮对话框!")
            .setNeutralButton("左") {
    
     dialog: DialogInterface?, which: Int -> showMessage(view,"左") }
            .setPositiveButton("右") {
    
     dialog: DialogInterface?, which: Int -> showMessage(view,"右") }.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

MaterialAlertDialogBuilder(this)
            .setItems(items) {
    
     dialog: DialogInterface?, which: Int -> showMessage(view,"点击了列表对话框的 " + 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:

MaterialAlertDialogBuilder(this)
            .setTitle("单选对话框")
            .setSingleChoiceItems(items,0) {
    
     dialog: DialogInterface?, which: Int ->
                singleSelectResult = items[which]
            }
            .setPositiveButton("确定") {
    
     dialog: DialogInterface?, which: Int ->
                showMessage(view,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)
MaterialAlertDialogBuilder(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(view,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

No radius dialog

MaterialAlertDialogBuilderThe default dialog box style is with radius, what should I do if I want to remove it?

MaterialAlertDialogBuilderNo setRadius(int radius), you need to change your mind. For example, create a drawable and Backgroundtry changing it.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
	<!-- 背景颜色为白色 -->
    <solid android:color="@color/white"/>
</shape>
use methods Describe
setBackground(Drawable background) Modify dialog box background

The effect is as follows:

Insert image description here

MaterialAlertDialogBuilder attributes

Click to go to Android official website to view all properties of MaterialAlertDialogBuilder

date time series

time picker

MaterialTimePicker

Insert image description here
Insert image description here

Implementation code:

MaterialTimePicker.Builder().build().show(supportFragmentManager,"1")
MaterialTimePickerProperty

Click to go to Android official website to view all properties of MaterialTimePicker

date picker

MaterialDatePicker

Insert image description here
Insert image description here

Implementation code:

MaterialDatePicker.Builder.datePicker().build().show(supportFragmentManager,"1")
MaterialDatePickerProperty

Click to go to Android official website to view all properties of MaterialDatePicker

bottom dialog box

The bottom dialog box is implemented BottomSheetDialogand is simple to use. Create a layout file named bottom_sheet_dialog.xml, instantiate it BottomSheetDialogand you are almost done!

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="bottom|center_horizontal"
    android:background="@null"
    android:orientation="vertical">

    <TextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:gravity="center"
        android:text="标题"
        android:textStyle="bold"
        android:background="@null"/>

    <View
        android:layout_width="match_parent"
        android:layout_height="1px"
        android:background="#C8C2C2" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="35dp"
        android:gravity="center"
        android:text="Item 1" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="35dp"
        android:gravity="center"
        android:text="Item 2" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="35dp"
        android:gravity="center"
        android:text="Item 3" />

</LinearLayout>
val dialog = BottomSheetDialog (this);
dialog.setContentView(R.layout.bottom_sheet_dialog)
dialog.show()

The effect is as shown in the figure:
Insert image description here
BottomSheetDialog It is so simple to use, but if you want to try to modify its background, newcomers will usually step into a pit, that is, the radius of the background cannot be modified, which is caused by the built-in background BottomSheetDialog ( Similar to the problems caused by other Dialog custom radii), at this time we need to hide the BottomSheetDialog built-in background.

However, BottomSheetDialogthere is no way to modify the background. To modify BottomSheetDialogthe background, you have to rely on inheriting BottomSheetDialogFragmentthe class and rewriting it onCreate(savedInstanceState: Bundle?), onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?)and creating a new style to overwrite the original style, as follows:

class CustomBottomSheetDialogFragment : BottomSheetDialogFragment() {
    
    

    override fun onCreate(savedInstanceState: Bundle?) {
    
    
        super.onCreate(savedInstanceState)
        // 可选的style:STYLE_NORMAL, STYLE_NO_TITLE, STYLE_NO_FRAME, STYLE_NO_INPUT.
        setStyle(STYLE_NORMAL, R.style.BottomSheetDialog)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    
    
        return inflater.inflate(R.layout.bottom_sheet_dialog, container, false)
    }
}

Create a new style in themes.xml

<!--实现BottomSheetDialog圆角效果-->
<style name="BottomSheetDialog" parent="Theme.Design.Light.BottomSheetDialog">
    <item name="bottomSheetStyle">@style/bottomSheetStyleWrapper</item>
</style>

<style name="bottomSheetStyleWrapper" parent="Widget.Design.BottomSheet.Modal">
    <item name="android:background">@android:color/transparent</item>
</style>

Then return to the interface to instantiate the dialog box and display it

val bottomSheetDialog = CustomBottomSheetDialogFragment()
        bottomSheetDialog.show(supportFragmentManager, "1")

The final effect is as follows:

Insert image description here

Precautions

1. You should consider whether to use Material Design in the early stages of development. Once you decide to use Material Design, most components of the App should use Material Design to avoid UI fragmentation as much as possible.


Click to download source code

Reference documents:
1. Material official website
2. Introduction to Android Material components
3. Detailed explanation of using BottomSheetDialog
4. Material Android official website (Dialogs)

Guess you like

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