How to _really_ programmatically change primary and accent color in Android Lollipop?

The question:

First of all, this question asks a very similar question. However, my question has a subtle difference.

What I’d like to know is whether it is possible to programmatically change the colorPrimary attribute of a theme to an arbitrary color?

So for example, we have:

<style name="AppTheme" parent="android:Theme.Material.Light">
    <item name="android:colorPrimary">#ff0000</item>
    <item name="android:colorAccent">#ff0000</item>

At runtime, the user decides he wants to use #ccffff as a primary color. Ofcourse there’s no way I can create themes for all possible colors.

I don’t mind if I have to do hacky stuff, like relying on Android’s private internals, as long as it works using the public SDK.

My goal is to eventually have the ActionBar and all widgets like a CheckBox to use this primary color.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

Themes are immutable, you can’t.

Method 2

I read the comments about contacts app and how it use a theme for each contact.

Probably, contacts app has some predefine themes (for each material primary color from here:

You can apply a theme before a the setContentView method inside onCreate method.

Then the contacts app can apply a theme randomly to each user.

This method is:


But this method has a problem, for example it can change the toolbar color, the scroll effect color, the ripple color, etc, but it cant change the status bar color and the navigation bar color (if you want to change it too).

Then for solve this problem, you can use the method before and:

if (Build.VERSION.SDK_INT >= 21) {

This two method change the navigation and status bar color.
Remember, if you set your navigation bar translucent, you can’t change its color.

This should be the final code:

protected void onCreate(Bundle savedInstanceState) {
    if (Build.VERSION.SDK_INT >= 21) {


You can use a switch and generate random number to use random themes, or, like in contacts app, each contact probably has a predefine number associated.

A sample of theme:

<style name="MyRandomTheme" parent="Theme.AppCompat.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/myrandomcolor1</item>
    <item name="colorPrimaryDark">@color/myrandomcolor2</item>
    <item name="android:navigationBarColor">@color/myrandomcolor1</item>

Method 3

You can use Theme.applyStyle to modify your theme at runtime by applying another style to it.

Let’s say you have these style definitions:

<style name="DefaultTheme" parent="Theme.AppCompat.Light">
    <item name="colorPrimary">@color/md_lime_500</item>
    <item name="colorPrimaryDark">@color/md_lime_700</item>
    <item name="colorAccent">@color/md_amber_A400</item>

<style name="OverlayPrimaryColorRed">
    <item name="colorPrimary">@color/md_red_500</item>
    <item name="colorPrimaryDark">@color/md_red_700</item>

<style name="OverlayPrimaryColorGreen">
    <item name="colorPrimary">@color/md_green_500</item>
    <item name="colorPrimaryDark">@color/md_green_700</item>

<style name="OverlayPrimaryColorBlue">
    <item name="colorPrimary">@color/md_blue_500</item>
    <item name="colorPrimaryDark">@color/md_blue_700</item>

Now you can patch your theme at runtime like so:

getTheme().applyStyle(, true);

The method applyStylehas to be called before the layout gets inflated! So unless you load the view manually you should apply styles to the theme before calling setContentView in your activity.

Of course this cannot be used to specify an arbitrary color, i.e. one out of 16 million (2563) colors. But if you write a small program that generates the style definitions and the Java code for you then something like one out of 512 (83) should be possible.

What makes this interesting is that you can use different style overlays for different aspects of your theme. Just add a few overlay definitions for colorAccent for example. Now you can combine different values for primary color and accent color almost arbitrarily.

You should make sure that your overlay theme definitions don’t accidentally inherit a bunch of style definitions from a parent style definition. For example a style called AppTheme.OverlayRed implicitly inherits all styles defined in AppTheme and all these definitions will also be applied when you patch the master theme. So either avoid dots in the overlay theme names or use something like Overlay.Red and define Overlay as an empty style.

Method 4

I’ve created some solution to make any-color themes, maybe this can be useful for somebody. API 9+

1. first create “res/values-v9/” and put there this file: styles.xml
and regular “res/values” folder will be used with your styles.

2. put this code in your res/values/styles.xml:

    <style name="AppTheme" parent="Theme.AppCompat.Light">
        <item name="colorPrimary">#000</item>
        <item name="colorPrimaryDark">#000</item>
        <item name="colorAccent">#000</item>
        <item name="android:windowAnimationStyle">@style/WindowAnimationTransition</item>

    <style name="AppThemeDarkActionBar" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorPrimary">#000</item>
        <item name="colorPrimaryDark">#000</item>
        <item name="colorAccent">#000</item>
        <item name="android:windowAnimationStyle">@style/WindowAnimationTransition</item>

    <style name="WindowAnimationTransition">
        <item name="android:windowEnterAnimation">@android:anim/fade_in</item>
        <item name="android:windowExitAnimation">@android:anim/fade_out</item>

3. in to AndroidManifest:

<application android:theme="@style/AppThemeDarkActionBar">

4. create a new class with name “”

public class ThemeColors {

    private static final String NAME = "ThemeColors", KEY = "color";

    public int color;

    public ThemeColors(Context context) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(NAME, Context.MODE_PRIVATE);
        String stringColor = sharedPreferences.getString(KEY, "004bff");
        color = Color.parseColor("#" + stringColor);

        if (isLightActionBar()) context.setTheme(;
        context.setTheme(context.getResources().getIdentifier("T_" + stringColor, "style", context.getPackageName()));

    public static void setNewThemeColor(Activity activity, int red, int green, int blue) {
        int colorStep = 15;
        red = Math.round(red / colorStep) * colorStep;
        green = Math.round(green / colorStep) * colorStep;
        blue = Math.round(blue / colorStep) * colorStep;

        String stringColor = Integer.toHexString(Color.rgb(red, green, blue)).substring(2);
        SharedPreferences.Editor editor = activity.getSharedPreferences(NAME, Context.MODE_PRIVATE).edit();
        editor.putString(KEY, stringColor);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) activity.recreate();
        else {
            Intent i = activity.getPackageManager().getLaunchIntentForPackage(activity.getPackageName());

    private boolean isLightActionBar() {// Checking if title text color will be black
        int rgb = ( + + / 3;
        return rgb > 210;

5. MainActivity:

public class MainActivity extends AppCompatActivity {

    protected void onCreate(Bundle savedInstanceState) {
        new ThemeColors(this);

    public void buttonClick(View view){
        int red= new Random().nextInt(255);
        int green= new Random().nextInt(255);
        int blue= new Random().nextInt(255);
        ThemeColors.setNewThemeColor(MainActivity.this, red, green, blue);

To change color, just replace Random with your RGB, Hope this helps.

How to _really_ programmatically change primary and accent color in Android Lollipop?

There is a complete example:

You can have a look at this GitHub project from Rumit Patel.

Method 5

I used the Dahnark’s code but I also need to change the ToolBar background:

if (dark_ui) {

    if (Build.VERSION.SDK_INT >= 21) {
} else {


toolbar = (Toolbar) findViewById(;

if(dark_ui) {

Method 6

You can change define your own themes, or customize existing android themes in res > values > themes, find where it says primary color and point it to the color defined in color.xml you want

How to _really_ programmatically change primary and accent color in Android Lollipop?

 <style name="Theme.HelloWorld" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
    <!-- Primary brand color. -->
    <item name="colorPrimary">@color/my_color</item>
    <item name="colorPrimaryVariant">@color/my_color</item>
    <item name="colorOnPrimary">@color/white</item>

Method 7

You cannot change the color of colorPrimary, but you can change the theme of your application by adding a new style with a different colorPrimary color

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>

<style name="AppTheme.NewTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/colorOne</item>
    <item name="colorPrimaryDark">@color/colorOneDark</item>

and inside the activity set theme


Method 8

from an activity you can do:

getWindow().setStatusBarColor(i color);

Method 9


You can set a custom toolbar item color dynamically by creating a custom toolbar class:

package view;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

public class CustomToolbar extends Toolbar{

    public CustomToolbar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        // TODO Auto-generated constructor stub

    public CustomToolbar(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub

    public CustomToolbar(Context context) {
        // TODO Auto-generated constructor stub
        ctxt = context;

    int itemColor;
    Context ctxt;

    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        Log.d("LL", "onLayout");
        super.onLayout(changed, l, t, r, b);
        colorizeToolbar(this, itemColor, (Activity) ctxt);

    public void setItemColor(int color){
        itemColor = color;
        colorizeToolbar(this, itemColor, (Activity) ctxt);

     * Use this method to colorize toolbar icons to the desired target color
     * @param toolbarView toolbar view being colored
     * @param toolbarIconsColor the target color of toolbar icons
     * @param activity reference to activity needed to register observers
    public static void colorizeToolbar(Toolbar toolbarView, int toolbarIconsColor, Activity activity) {
        final PorterDuffColorFilter colorFilter
                = new PorterDuffColorFilter(toolbarIconsColor, PorterDuff.Mode.SRC_IN);

        for(int i = 0; i < toolbarView.getChildCount(); i++) {
            final View v = toolbarView.getChildAt(i);

            doColorizing(v, colorFilter, toolbarIconsColor);

      //Step 3: Changing the color of title and subtitle.

    public static void doColorizing(View v, final ColorFilter colorFilter, int toolbarIconsColor){
        if(v instanceof ImageButton) {

        if(v instanceof ImageView) {

        if(v instanceof AutoCompleteTextView) {

        if(v instanceof TextView) {

        if(v instanceof EditText) {

        if (v instanceof ViewGroup){
            for (int lli =0; lli< ((ViewGroup)v).getChildCount(); lli ++){
                doColorizing(((ViewGroup)v).getChildAt(lli), colorFilter, toolbarIconsColor);

        if(v instanceof ActionMenuView) {
            for(int j = 0; j < ((ActionMenuView)v).getChildCount(); j++) {

                //Step 2: Changing the color of any ActionMenuViews - icons that
                //are not back button, nor text, nor overflow menu icon.
                final View innerView = ((ActionMenuView)v).getChildAt(j);

                if(innerView instanceof ActionMenuItemView) {
                    int drawablesCount = ((ActionMenuItemView)innerView).getCompoundDrawables().length;
                    for(int k = 0; k < drawablesCount; k++) {
                        if(((ActionMenuItemView)innerView).getCompoundDrawables()[k] != null) {
                            final int finalK = k;

                            //Important to set the color filter in seperate thread, 
                            //by adding it to the message queue
                            //Won't work otherwise. 
                            //Works fine for my case but needs more testing

                            ((ActionMenuItemView) innerView).getCompoundDrawables()[finalK].setColorFilter(colorFilter);

//                     Runnable() {
//                                  @Override
//                                  public void run() {
//                                      ((ActionMenuItemView) innerView).getCompoundDrawables()[finalK].setColorFilter(colorFilter);
//                                  }
//                              });


then refer to it in your layout file. Now you can set a custom color using



I found the information to do this here: How to dynamicaly change Android Toolbar icons color

and then I edited it, improved upon it, and posted it here: GitHub:AndroidDynamicToolbarItemColor

Method 10

This is what you CAN do:

write a file in drawable folder, lets name it background.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="" >
    <solid android:color="?attr/colorPrimary"/>

then set your Layout’s (or what so ever the case is) android:background="@drawable/background"

on setting your theme this color would represent the same.

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment