在我正在开发的一个应用程序中,我想要做的就是改变AlertDialog按钮的高亮颜色。我的主要情报来源是this讨论,但我也在StackOverflow上阅读了几乎每一篇关于这方面的文章。下面的代码运行时不会崩溃,但按钮的突出显示颜色仍然是默认的橙黄色。有谁知道哪里出了问题吗?
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message).setCancelable(true)
.setPositiveButton(getResources().getString(R.string.positive_button_title), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
// Do stuff
}
});
// Incredibly bulky way of simply changing the button highlight color,
// but it appears to be the only way we can do it without getting a NullPointerException
AlertDialog dialog = builder.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialogInterface) {
if (Build.VERSION.SDK_INT < 16) {
((AlertDialog) dialogInterface).getButton(AlertDialog.BUTTON_POSITIVE).setBackgroundDrawable(getResources().getDrawable(R.drawable.dialog_button_drawable));
} else {
((AlertDialog) dialogInterface).getButton(AlertDialog.BUTTON_POSITIVE).setBackground(getResources().getDrawable(R.drawable.dialog_button_drawable));
}
}
});
dialog.show();
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/custom_button_background" android:state_focused="true" android:state_pressed="false" />
<item android:drawable="@android:drawable/btn_default" android:state_focused="true" android:state_pressed="true" />
<item android:drawable="@android:drawable/btn_default" android:state_focused="false" android:state_pressed="true" />
<item android:drawable="@android:drawable/btn_default" />
</selector>发布于 2017-01-25 19:21:19
在创建AlertDialog时,您可以设置要使用的主题。
对话框示例-创建对话框
AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.MyAlertDialogStyle);
builder.setTitle("AppCompatDialog");
builder.setMessage("");
builder.setPositiveButton("OK", null);
builder.setNegativeButton("Cancel", null);
builder.show();styles.xml -自定义样式
<style name="MyAlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
<!-- Used for the buttons -->
<item name="colorAccent">#FFC107</item>
<!-- Used for the title and text -->
<item name="android:textColorPrimary">#FFFFFF</item>
<!-- Used for the background -->
<item name="android:background">#4CAF50</item>
</style>要更改标题的外观,可以执行以下操作。首先添加一个新样式:
<style name="MyTitleTextStyle">
<item name="android:textColor">#FFEB3B</item>
<item name="android:textAppearance">@style/TextAppearance.AppCompat.Title</item>
</style>之后,只需在MyAlertDialogStyle中引用此样式
<style name="MyAlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
...
<item name="android:windowTitleStyle">@style/MyTitleTextStyle</item>
</style>这样你就可以通过android为消息定义一个不同的textColor :textColorPrimary,并通过样式为标题定义一个不同的样式。
https://stackoverflow.com/questions/26974050
复制相似问题