如何使MaterialAlertDialogBu​​ilder居中对齐标题,消息和按钮

时间:2020-06-24 19:22:20

标签: java android kotlin android-alertdialog material-components-android

如何使居中对齐标题,消息和按钮

MaterialAlertDialogBuilder(requireContext())
                .setTitle("Message")
                .setMessage("This is info message.")
                .setPositiveButton("Ok") { dialog, which ->
             
                }
                
                .show()

3 个答案:

答案 0 :(得分:4)

您可以使用标题和消息:

    <style name="MaterialAlertDialog__Center" parent="@style/ThemeOverlay.MaterialComponents.MaterialAlertDialog">
        <item name="materialAlertDialogTitlePanelStyle">@style/Title.Panel.Center</item>
        <item name="materialAlertDialogBodyTextStyle">@style/Message.Center</item>
    </style>

    <style name="Title.Panel.Center" parent="MaterialAlertDialog.MaterialComponents.Title.Panel">
        <item name="android:gravity">center_horizontal</item>
    </style>

    <style name="Message.Center" parent="MaterialAlertDialog.MaterialComponents.Body.Text">
        <item name="android:gravity">center_horizontal</item>
    </style>

具有:

MaterialAlertDialogBuilder(this, R.style.MaterialAlertDialog_Center)
                .setTitle("Message")
                ..
                .show()

enter image description here

答案 1 :(得分:0)

您可以创建自己的布局并将其添加到对话框中

val inflater=LayoutInflater.from(requireContext())
//Getting the custom view
val view=inflater.inflate(R.layout.YOUR_CUSTOM_LAYOUT,null)
//Obtaining the components
val title=view.findViewById(R.id.YOUR_CUSTOM_TILE)
title.text="Message"
val button=view.findViewById(R.id.YOUR_CUSTOM_BUTTON)
button.setOnCLickListener{
    //onClick
    }
val dialog=MaterialAlertDialogBuilder(requireContext()).setView(view).create()
dialog.show()

答案 2 :(得分:0)

要使标题和消息居中,只需在主题中进行更改

<item name="materialAlertDialogTheme">@style/ThemeOverlay.MaterialComponents.MaterialAlertDialog.Centered</item>