其他分享
首页 > 其他分享> > Android:如何在不使用自定义布局的情况下更改AlertDialog标题文本颜色和背景颜色?

Android:如何在不使用自定义布局的情况下更改AlertDialog标题文本颜色和背景颜色?

作者:互联网

我想在不使用自定义布局的情况下更改AlertDialog标题颜色和背景颜色.我的要求

I want like this

我尝试了以下代码,但无法正常工作.

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 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();

Custom Alert Dialog Header

标签:textcolor,alertdialog,background-color,android
来源: https://codeday.me/bug/20191108/2009899.html