"windowTitleBackgroundStyle" 不适用于 AlertDialog 标题

"windowTitleBackgroundStyle" Doesn't Work on AlertDialog Title

我的风格

<style name="myAlertDialog" parent="Theme.AppCompat.Light.Dialog.Alert">
    <item name="android:windowTitleBackgroundStyle">@color/colorPrimary</item>
</style>

我的AlertDialog

AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext(), R.style.myAlertDialog);

builder.setTitle("Dialog Title");
builder.setMessage("This is message!");

builder.create().show();

我的自定义样式完全没有效果。有帮助吗?

网上查了很多关于这个问题,发现windowTitleBackgroundStyle不行,但是windowTitleStyle可以,结果不是我想要的:

<style name="myAlertDialog" parent="Theme.AppCompat.Light.Dialog.Alert">
    <item name="android:windowTitleStyle">@style/myDialogTitle</item>
</style>

<style name="myDialogTitle" parent="TextAppearance.AppCompat.Title">
    <item name="android:background">@color/colorPrimary</item>
</style>

看起来整个 AlertDialog 布局中都有固定的填充。除此之外,getResource().getIdentifier()findViewById() 方法目前还不起作用。因此,setCustomTitle()成为修改AlertDialog.

标题的唯一方法

1.为 AlertDialog

创建自定义标题布局
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_red_light"
    android:orientation="vertical"
    android:paddingStart="24dp"                         //following Material Design guideline
    android:paddingTop="16dp"
    android:paddingEnd="24dp"
    android:paddingBottom="16dp">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Marvel Cinematic Universe"
        android:textAppearance="@style/TextAppearance.AppCompat.Title"      //key point 1, using AlertDialog default text style
        android:textColor="@android:color/white" />

</LinearLayout>

2。使用 "setCustomTitle()"

将自定义标题布局应用于 AlertDialog
AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
View titleView = getLayoutInflater().inflate(R.layout.dialog_title, null);

builder.setCustomTitle(titleView);                      //key point 2
builder.setMessage(R.string.main_marvel_info);
builder.setPositiveButton("OK", null);

builder.create().show();