I want to customize toolbar title text color dynamically.
I had tried following methods, but all methods below failed.
I had also tried to set color before running setSupportActionBar(toolbar)
, but still failed.
I had also searched and tried methods from Stack Overflow, but all also failed.
How can I do?
textColor = Color.parseColor("#00FF00")
toolbar.setTitleTextColor(textColour)
textColor = Color.parseColor("#00FF00")
(toolbar::class.java.getDeclaredField("mTitleTextView")
.apply { isAccessible = true }
.get(toolbar) as TextView)
.setTextColor(textColour)
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:id="@+id/toolbar"
app:titleTextColor="#00FF00"
app:popupTheme="@style/AppTheme.PopupOverlay"
app:layout_collapseMode="pin" />
The problem was solved that I read through source code of CollapsingToolbarLayout
, when there is CollapsingToolbarLayout
applied, should not change title text color with Toolbar
function setTitleTextColor()
, but with methods setCollapsedTitleTextColor()
and setExpandedTitleColor()
of CollapsingToolbarLayout
.
Following is my code.
val textColor = Color.parseColor("#00FF00")
collapsingToolbarLayout.setExpandedTitleColor(textColor)
collapsingToolbarLayout.setCollapsedTitleTextColor(textColor)
<com.google.android.material.appbar.CollapsingToolbarLayout
android:layout_width="match_parent"
android:layout_height="270dp"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:toolbarId="@id/toolbar"
android:id="@+id/collapsingToolbarLayout">
...
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:id="@+id/toolbar"
app:popupTheme="@style/AppTheme.PopupOverlay"
app:titleTextColor="@color/black"
app:layout_collapseMode="pin" />
...
</com.google.android.material.appbar.CollapsingToolbarLayout>