2019 年 8 月更新了 Android 库的 Material 组件:
随着新Android 库的 Material 组件你可以使用新的com.google.android.material.dialog.MaterialAlertDialogBuilder类,从现有的扩展androidx.appcompat.AlertDialog.Builder类并提供对最新材料设计规范的支持。
只需使用这样的东西:
new MaterialAlertDialogBuilder(context)
.setTitle("Dialog")
.setMessage("Lorem ipsum dolor ....")
.setPositiveButton("Ok", /* listener = */ null)
.setNegativeButton("Cancel", /* listener = */ null)
.show();
您可以自定义颜色扩展ThemeOverlay.MaterialComponents.MaterialAlertDialog
style:
<style name="CustomMaterialDialog" parent="@style/ThemeOverlay.MaterialComponents.MaterialAlertDialog">
<!-- Background Color-->
<item name="android:background">#006db3</item>
<!-- Text Color for title and message -->
<item name="colorOnSurface">@color/secondaryColor</item>
<!-- Text Color for buttons -->
<item name="colorPrimary">@color/white</item>
....
</style>
应用您的自定义样式只需使用构造函数:
new MaterialAlertDialogBuilder(context, R.style.CustomMaterialDialog)
To 自定义按钮、标题和正文 检查这个帖子更多细节。
您还可以更改globally您的应用程序主题中的样式:
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.MaterialComponents.Light">
...
<item name="materialAlertDialogTheme">@style/CustomMaterialDialog</item>
</style>
带有支持库和APPCOMPAT主题:
随着新AppCompat v22.1
你可以使用新的android.support.v7.app.AlertDialog.
只需使用这样的代码:
import android.support.v7.app.AlertDialog
AlertDialog.Builder builder =
new AlertDialog.Builder(this, R.style.AppCompatAlertDialogStyle);
builder.setTitle("Dialog");
builder.setMessage("Lorem ipsum dolor ....");
builder.setPositiveButton("OK", null);
builder.setNegativeButton("Cancel", null);
builder.show();
并使用这样的样式:
<style name="AppCompatAlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="colorAccent">#FFCC00</item>
<item name="android:textColorPrimary">#FFFFFF</item>
<item name="android:background">#5fa3d0</item>
</style>
否则,您可以在当前主题中定义:
<style name="AppTheme" parent="Theme.AppCompat.Light">
<!-- your style -->
<item name="alertDialogTheme">@style/AppCompatAlertDialogStyle</item>
</style>
然后在你的代码中:
import android.support.v7.app.AlertDialog
AlertDialog.Builder builder =
new AlertDialog.Builder(this);
Here the AlertDialog on Kitkat: