怎样设置AlertDialog的按钮颜色

   2024-09-30 8160
核心提示:要更改Android AlertDialog中按钮的颜色,请遵循以下步骤:首先,在res/values文件夹中创建或打开一个名为colors.xml的文件。如

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

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

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号