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

前端 未结 5 2139
南笙
南笙 2020-12-18 18:11

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

getSupportActionBar().setBackgroundDrawable(newColorDrawable(getResources()         


        
相关标签:
5条回答
  • 2020-12-18 18:33

    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

    0 讨论(0)
  • 2020-12-18 18:45

    In my style I changed

            <item name="android:background">@color/background</item>
    

    to

            <item name="android:windowBackground">@color/background</item>
    

    and that seems to have fixed it for me.

    0 讨论(0)
  • 2020-12-18 18:47
    mToolbar.setBackgroundResource(mGameEnum.getPrimeColorRes());
    
    0 讨论(0)
  • 2020-12-18 18:54

    Late, but I hope it would be helpful comment

    I had this item in my Activity style

    <item name="android:background">someColor</item>
    

    so when I changed toolbar color, title and menu items didn't change background. I just removed this item and now it works perfect.

    I did not have time to understand the details, but I think it might be useful to someone else.

    0 讨论(0)
  • 2020-12-18 18:58

    use this to access the 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 
                }
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题