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

Sag*_*ala 10 android textcolor background-color android-alertdialog

我想在不使用自定义布局的情况下更改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));
}
Run Code Online (Sandbox Code Playgroud)

用下面我试图线,但它总是返回nullfindViewById

int textViewId = dialog.getContext().getResources().getIdentifier("android:id/alertTitle", null, null);
TextView tv = dialog.findViewById(textViewId);
Run Code Online (Sandbox Code Playgroud)

我也尝试使用,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>
Run Code Online (Sandbox Code Playgroud)

Ani*_*bla 13

您可以在警报对话框中使用自定义标题:

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();
Run Code Online (Sandbox Code Playgroud)

自定义警报对话框标题

  • 我的问题是不使用自定义布局,但它是一个很好的解决方案。现在我可以使用这个。谢谢。 (2认同)

小智 5

检查示例图像

您可以使用自定义主题更改警报对话框标题、背景和按钮颜色的颜色。

   <style name="CustomDialogTheme" parent="Theme.AppCompat.Light.Dialog.Alert"> 
        <item name="android:windowBackground">@android:color/black</item>
        <item name="colorAccent">@android:color/white</item>
        <item name="android:textColorPrimary">@android:color/white</item>
    </style>
Run Code Online (Sandbox Code Playgroud)

android: windowBackground 改变背景颜色

colorAccent 更改按钮颜色

android:textColorPrimary 更改对话框标题颜色

将此主题应用于对话框

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.CustomDialogTheme);
Run Code Online (Sandbox Code Playgroud)

  • 对于“AlertDialog”标题没有帮助。 (2认同)