我想在不使用自定义布局的情况下更改AlertDialog
标题颜色 和背景颜色。我的要求,
我尝试了下面的代码,但无法正常工作。
final CharSequence[] items = {" Visiting Card", "Prescription Letter"};
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setMessage(message)
.setTitle(title).setCancelable(false);
builder.setItems(items, (dialog, item) -> {
});
AlertDialog dialog = builder.create();
dialog.show();
int textViewId = dialog.getContext().getResources().getIdentifier("android:id/alertTitle", null, null);
TextView tv = dialog.findViewById(textViewId); // It always returns null
if (tv != null) {
tv.setTextColor(activity.getResources().getColor(R.color.white));
tv.setBackgroundColor(activity.getResources().getColor(R.color.colorPrimary));
}
我尝试使用以下行,但它总是在 findViewById
中返回 null
,
int textViewId = dialog.getContext().getResources().getIdentifier("android:id/alertTitle", null, null);
TextView tv = dialog.findViewById(textViewId);
我也试过使用 style
但它只会改变标题文本的颜色,
<style name="AppCompatAlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="colorAccent">@color/colorAccent</item>
<item name="android:background">#ffffff</item>
<item name="android:textColor">@color/white</item>
<item name="android:headerBackground">@color/colorPrimary</item>
</style>
最佳答案
您可以在警报对话框中使用自定义标题:
TextView textView = new TextView(context);
textView.setText("Select an option");
textView.setPadding(20, 30, 20, 30);
textView.setTextSize(20F);
textView.setBackgroundColor(Color.CYAN);
textView.setTextColor(Color.WHITE);
final CharSequence[] items = {"Visiting Card", "Prescription Letter"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setCustomTitle(textView);
builder.setItems(items, (dialog, item) -> {
}).show();
关于Android:如何在不使用自定义布局的情况下更改 AlertDialog 标题文本颜色和背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51380128/