Java – You cannot change the color of the toolbar

You cannot change the color of the toolbar… here is a solution to the problem.

You cannot change the color of the toolbar

Can anyone explain why my toolbar didn’t change its color, even though I created another style like :

<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">false</item>
</style>

Add it to my list file, for example:

<activity
    android:name=". SettingsActivity"
    android:label="@string/title_activity_settings"
    android:parentActivityName=". MainActivity">
    <meta-data
        android:theme="@style/AppTheme.NoActionBar"
        android:name="android.support.PARENT_ACTIVITY"
        android:value="com.com.com.com.MainActivity" />
</activity>

And try changing the toolbar like this:

Toolbar toolbar = new Toolbar(this);
toolbar.setBackgroundColor(getResources().getColor(R.color.light_blue));
setSupportActionBar(toolbar);

But got it anyway

This Activity already has an action bar supplied by the window decor.
Do not request Window.FEATURE_ACTION_BAR and set windowActionBar to
false in your theme to use a Toolbar instead.

I even tried getSupportActionBar().hide(); But it still doesn’t work.

XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.com.com.com.SettingsActivity"
    android:id="@+id/settings_activity">
</RelativeLayout>

Basically, what I want is to keep my global theme and change the toolbar color in only one of the activities. That’s why I don’t create the toolbar in an xml file, I create it programmatically, add a background color and want to set it.

Solution

You need to remove android:theme="@style/AppTheme.NoActionBar" from the meta-data tag

  <activity
        android:name=". SettingsActivity"
        android:label="@string/title_activity_settings"
        android:theme="@style/AppTheme.NoActionBar"
        android:parentActivityName=". MainActivity">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="net.noorr.menote.menote.MainActivity" />
    </activity>

In java code:

Toolbar toolbar = (Toolbar) findViewById(R.id.yourToolbarId);
toolbar.setBackgroundColor(getResources().getColor(R.color.light_blue));
setSupportActionBar(toolbar);

Related Problems and Solutions