Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

android - Change Toolbar background color programmatically does not change Toolbar Title Background color

I′m trying to change the toolbar Background color programmatically by doing this:

getSupportActionBar().setBackgroundDrawable(newColorDrawable(getResources().getColor(R.color.test_color_blue)));

And this is the result:

before:

enter image description here

After:

enter image description here

Some how the toolbar title still has the same background color as before.

here is my toolbar xml:

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
app:theme="@style/Theme.Toolbar">

And here is the Theme:

<style name="Theme.Toolbar" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
    <item name="android:maxHeight">@dimen/abc_action_bar_default_height_material</item>
    <item name="android:background">@color/primary</item>
    <item name="colorPrimary">@color/primary</item>
    <item name="colorPrimaryDark">@color/primary_dark</item>
    <item name="colorAccent">@android:color/white</item>
    <item name="titleTextAppearance">@style/Theme.Toolbar.Title</item>
</style>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Change your code as follows:

toolbar.xml

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
        style="@style/MyToolbarStyle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical">

Theme / Style

<style name="MyToolbarStyle">
    <item name="android:maxHeight">@dimen/abc_action_bar_default_height_material</item>
    <item name="android:background">@color/primary</item>
    <item name="popupTheme">@style/ThemeOverlay.AppCompat.Light</item>
    <item name="titleTextAppearance">@style/Theme.Toolbar.Title</item>
    <!-- No need for colorPrimary, colorPrimaryDark, colorAccent here
         this should go to the AppTheme -->
</style>

Result

Before setting the new background color:

picture before background color change

and after:

picture after background color change


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...