2015-04-06 113 views
20

我正尝试做这种编程方式更改的工具栏背景颜色:更改工具栏的背景色编程不改变工具栏标题背景颜色

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

这是结果:

前:

enter image description here

后:

enter image description here

一些如何工具栏标题仍然具有与以前相同的背景颜色。

这里是我的工具栏的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"> 

这里是主题:

<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> 
+0

您是否在styles.xml中为操作栏应用了任何自定义样式,可能其中一些是冲突的。 – Harry 2015-04-06 09:10:54

+0

张贴您的布局xml请 – 2015-04-06 14:27:36

+0

@DavidJhons我已经发布了有关问题的新细节 – EkKoZ 2015-04-06 15:11:47

回答

4

使用这种访​​问的TextView

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 
      } 
     } 
    } 
} 
12

如下更改代码:

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"> 

主题/风格

<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> 

结果

年代以前ETTING新的背景色:

picture before background color change

后:

picture after background color change

+0

您在哪里放置了colorPrimary/PrimaryDark等,即您将“AppTheme”放置在哪里? 此外,有没有什么特别的原因,你不设置父母主题? – ThePersonWithoutC 2016-07-01 02:50:17

+1

它基本上只是一种自定义风格,我不想从其他主题继承任何属性,因此我没有指定父主题。关于'colorPrimary':这是在应用程序/活动使用的AppTheme中设置的。默认情况下,“工具栏”根据“colorPrimary”属性设置背景,除非您不用样式重写它。 – reVerse 2016-07-02 08:15:07

4

晚了,但我希望这将是有益的评论

我在我的活动风格

有这个 item
<item name="android:background">someColor</item> 

所以当我改变toolbar颜色时,标题和菜单项没有改变背景。 我刚刚删除了这个item,现在它完美。

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

0
mToolbar.setBackgroundResource(mGameEnum.getPrimeColorRes());