阅读量:137
要更改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按钮的颜色。使用上面定义的颜色资源来设置按钮的文本颜色:
- @color/green_button
- @color/red_button
</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中定义的颜色资源进行更改。