Android "app:titleTextColor" 在 CollapsingToolbarLayout 的 MaterialToolbar 中不起作用

Android "app:titleTextColor" Doesn't Work in MaterialToolbar within CollapsingToolbarLayout

<com.google.android.material.appbar.CollapsingToolbarLayout
    android:id="@+id/collapsingToolbarLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:contentScrim="@color/purple_500"
    app:layout_scrollFlags="scroll|exitUntilCollapsed">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"
        android:src="@drawable/sam" />

    <com.google.android.material.appbar.MaterialToolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?actionBarSize"
        app:title="Sam Chen"
        app:titleTextColor="@color/white"/>    //<- here, doesn't work

</com.google.android.material.appbar.CollapsingToolbarLayout>

结果:

并崩溃:

要在折叠和展开模式下更改 CollapsingToolbarLayout 的标题文本颜色,您可以使用属性 app:expandedTitleTextAppearanceapp:collapsedTitleTextAppearance 如下所示:

<com.google.android.material.appbar.CollapsingToolbarLayout
    android:id="@+id/collapsingToolbarLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:contentScrim="@color/purple_500"
    app:layout_scrollFlags="scroll|exitUntilCollapsed"
    app:expandedTitleTextAppearance="@style/MyExpandedTitle"
    app:collapsedTitleTextAppearance="@style/MyCollapsedTitle">

其中 @style/MyExpandedTitle 是您自定义的 expandedTitleTextAppearance,如下所示:

 <style name="MyExpandedTitle" parent="@style/TextAppearance.Design.CollapsingToolbar.Expanded">
        <item name="android:textColor">@android:color/holo_red_dark</item>
 </style>

@style/MyCollapsedTitle 是您自定义的 collapsedTitleTextAppearance,如下所示:

 <style name="MyCollapsedTitle" parent="@style/TextAppearance.AppCompat.Title">
        <item name="android:textColor">@android:color/holo_red_dark</item>
 </style>

这是针对我的案例的解决方案,我只需要将标题和选项菜单图标设为白色即可:

<com.google.android.material.appbar.CollapsingToolbarLayout

    ...

    android:theme="@style/ThemeOverlay.MaterialComponents.Dark.ActionBar">

要自定义标题和选项菜单图标的颜色可以阅读:How to change the Text color of collapsing toolbar and the back button color of collapsing toolbar in android

<com.google.android.material.appbar.CollapsingToolbarLayout
            ...
            app:collapsedTitleTextColor="@android:color/white"
            app:expandedTitleTextColor="@android:color/white">