Abuzaid Abuzaid - 1 year ago 59
Android Question

Change "ActionBar" color doesn't give the correct color

I am trying to change ActionBar color in my "AppBar Layout" programmatically, through this code:

toolbar.setBackgroundColor(R.color.hidden_bars); //#464445


but every time I end with different color, a darker version of the colorPrimary (#48bee6)

Here is my xml:

<android.support.design.widget.AppBarLayout
android:id="@+id/id_appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
app:layout_scrollFlags="enterAlwaysCollapsed" />

<android.support.design.widget.TabLayout
android:id="@+id/tabLayout"
style="@style/WenoTabLayout"
android:layout_width="match_parent"
android:layout_height="@dimen/tab_bar_height"
android:layout_marginTop="1dp"
android:background="@color/white"
app:tabGravity="fill"
app:tabMode="fixed" />

</android.support.design.widget.AppBarLayout>

Answer Source

This is a common misunderstanding of setBackgroundColor(int). The int value pass to setBackgroundColor should be color code instead of color resource id. You should get the color code by id first.

// Use this instead of context if you are in activity
int color = ContextCompat.getColor(context, R.color.your_color);   
toolbar.setBackgroundColor(color);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download