温馨提示×

怎样设置AlertDialog的按钮颜色

小樊
89
2024-09-04 16:48:42
栏目: 编程语言

要更改Android AlertDialog中按钮的颜色,请遵循以下步骤:

  1. 首先,在res/values文件夹中创建或打开一个名为colors.xml的文件。如果已经存在该文件,请跳过此步骤。
  2. colors.xml文件中,添加要用于按钮的颜色值。例如,添加绿色和红色按钮:
<?xml version="1.0" encoding="utf-8"?><resources>
   <color name="green_button">#4CAF50</color>
   <color name="red_button">#F44336</color>
</resources>
  1. res/values文件夹中创建或打开一个名为styles.xml的文件。如果已经存在该文件,请跳过此步骤。
  2. styles.xml文件中,添加一个新的样式以自定义AlertDialog按钮的颜色。使用上面定义的颜色资源来设置按钮的文本颜色:
    <item name="colorAccent">@color/green_button</item>
    <item name="android:textColorPrimary">@color/red_button</item>
</style>
  1. 最后,在Java或Kotlin代码中创建并显示AlertDialog时,应用自定义样式。以下是Java和Kotlin的示例:

Java 示例:

AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.CustomAlertDialogStyle));
builder.setMessage("Are you sure?")
       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
               // Your "Yes" action code here
           }
       })
       .setNegativeButton("No", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
               // Your "No" action code here
           }
       });
builder.create().show();

Kotlin 示例:

val builder = AlertDialog.Builder(ContextThemeWrapper(this, R.style.CustomAlertDialogStyle))
builder.setMessage("Are you sure?")
       .setPositiveButton("Yes") { dialog, id ->
           // Your "Yes" action code here
       }
       .setNegativeButton("No") { dialog, id ->
           // Your "No" action code here
       }
builder.create().show()

现在,当您运行应用程序并显示AlertDialog时,按钮颜色将根据您在styles.xml中定义的颜色资源进行更改。

0