以编程方式更改工具栏背景颜色不会更改工具栏标题背景颜色

EkK*_*KoZ 22 android android-actionbar android-toolbar

我试图通过这样做以编程方式更改工具栏背景颜色:

getSupportActionBar().setBackgroundDrawable(newColorDrawable(getResources().getColor(R.color.test_color_blue)));
Run Code Online (Sandbox Code Playgroud)

这就是结果:

之前:

在此输入图像描述

后:

在此输入图像描述

工具栏标题仍然具有与以前相同的背景颜色.

这是我的工具栏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">
Run Code Online (Sandbox Code Playgroud)

这是主题:

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

reV*_*rse 13

更改您的代码如下:

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

主题/风格

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

结果

在设置新背景颜色之前:

背景颜色变化前的图片

之后:

背景颜色变化后的图片


Igo*_*nov 5

迟到了,但我希望这会有所帮助

item我的活动风格中有这个

<item name="android:background">someColor</item>
Run Code Online (Sandbox Code Playgroud)

所以当我改变toolbar颜色时,标题和菜单项不会改变背景.我刚刚删除了它item,现在它完美无缺.

我没有时间了解细节,但我认为这可能对其他人有用.


小智 4

用它来访问文本视图

public void changeToggleTitle() {
    if (mToolbar != null) {
        for(int i= 0; i < mToolbar.getChildCount(); i++){
            View v = mToolbar.getChildAt(i);
            if(v != null && v instanceof TextView){
                TextView t = (TextView) v;
                // Do the magic 
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)