179

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

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.

12
  • 1
    You have no idea what "Android's private internals" are for a non-existent Android release. Do not assume that L's "private internals" are the same as those for whatever L turns into in terms of a production release. Sep 12, 2014 at 21:00
  • No, you can't place arbitrary data into a theme. That said, colorPrimary is only used for the action bar background, recents bar color, and notifications color and you can change all of these dynamically.
    – alanv
    Sep 12, 2014 at 21:20
  • 2
    I think you should ask "How to change style attribute in runtime", and from what I saw the answer is you cannot. However I have an idea that might help you. Use custom ContextWrapper and provide own Resources. Look at this: github.com/negusoft/holoaccent/blob/master/HoloAccent/src/com/… In overall this project might give you an idea how to do that.
    – Mikooos
    Sep 13, 2014 at 7:56
  • 1
    Just brainfarting here, but all XML gets converted into .dex files that are loaded into your android application as java objects right. Doesn't that mean we should be able to create and set entire themes from code as well as generate the theme from a factory yet to be written? Sounds like a lot of work.
    – G_V
    Oct 21, 2014 at 13:51
  • 1
    @NiekHaarman did you ever figure out a way?
    – gbhall
    Apr 7, 2015 at 4:42

10 Answers 10

220

Themes are immutable, you can't.

9
  • 12
    Thanks, Chris! Not the answer I was looking for, but I guess I'll have to live with it :)
    – nhaarman
    Oct 22, 2014 at 15:57
  • 5
    Hi @Chris Banes, but how did the contact app change the status bar color and toolbar color according to the contact's theme color? If it is possible, I think what Niek Haarman's need is not too far since he only need to store the color code that the user want. Could you please explain more on this? I also want to create something like this but am really confused with it.
    – Swan
    Oct 25, 2014 at 16:23
  • 42
    Status Bar color can be changed dynamically via Window.setStatusBarColor(). Oct 26, 2014 at 11:49
  • 9
    Is it possible to create a theme programmatically? Feb 6, 2015 at 17:53
  • 4
    And while changing status bar color dynamically you can also change navigation bar color via Window.setNavigationBarColor() - API 21 :)
    – user802421
    Apr 30, 2015 at 9:59
70

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: http://www.google.com/design/spec/style/color.html).

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:

setTheme(R.style.MyRandomTheme);

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) {
        getWindow().setNavigationBarColor(getResources().getColor(R.color.md_red_500));
        getWindow().setStatusBarColor(getResources().getColor(R.color.md_red_700));
    }

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:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTheme(R.style.MyRandomTheme);
    if (Build.VERSION.SDK_INT >= 21) {
        getWindow().setNavigationBarColor(getResources().getColor(R.color.myrandomcolor1));
        getWindow().setStatusBarColor(getResources().getColor(R.color.myrandomcolor2));
    }
    setContentView(R.layout.activity_main);

}

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>
</style>
2
  • 2
    Thank you for your answer. Unfortunately, my request was to use an arbitrary color. Of course it is not feasible to create themes for all colors.
    – nhaarman
    Jan 19, 2015 at 21:24
  • 1
    @DanielGomezRico - AFAIK you can override the pre-set theme regardless of where initially set - as long as you do it early enough. As answer says "You can apply a theme before the setContentView method inside onCreate method." Nov 29, 2019 at 21:34
61

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>

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

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

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

Now you can patch your theme at runtime like so:

getTheme().applyStyle(R.style.OverlayPrimaryColorGreen, 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.

5
  • 12
    Try calling applyStyle before calling setContentView in your activity and it should work.
    – devconsole
    Sep 27, 2016 at 5:46
  • 1
    yea okai, then it might work ! i'm searching for a way to change the coloraccent in fragment niveau not activity ! thats why it didn't work for me sadly :< My use case is that I want different colors for FAB or tab indicators when switching from tabs which will start a different fragment ! Sep 27, 2016 at 12:26
  • Thanks this helped a lot! However, I'm not able to do it multiple times. (one for colorPrimary, one for colorAccent, etc). Could you help me? Thanks. stackoverflow.com/questions/41779821/…
    – Thomas Vos
    Jan 21, 2017 at 13:34
  • 2
    That's the kind of answer for which I want to use a second account just to +1 once more. Thanks. Mar 25, 2018 at 21:58
  • Thank you so much, this was what i was looking for.... i hope i can change the Accent color of the current theme using this approach.
    – Nasib
    Nov 9, 2019 at 13:46
42

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:

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

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

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

3. in to AndroidManifest:

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

4. create a new class with name "ThemeColors.java"

public class ThemeColors {

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

    @ColorInt
    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(R.style.AppTheme);
        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);
        editor.apply();

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

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

5. MainActivity:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new ThemeColors(this);
        setContentView(R.layout.activity_main);
    }

    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.

enter image description here

There is a complete example: ColorTest.zip

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

14
  • can you share project like? Nov 1, 2018 at 14:59
  • 1
    I can't wrap my head around context.setTheme(context.getResources().getIdentifier("T_" + stringColor, "style", context.getPackageName())); can you give me a explaination or a link to follow up on this topic? Dec 25, 2018 at 13:35
  • 2
    @IQ.feature I think pushing your code to Github repo is more suitable for code sharing Dec 13, 2019 at 16:43
  • 14
    Just to be clear for others because I fell for this... there is a file res-v9/styles.xml which declares a whole list of themes with different colors and the code essentially applies one of those themes and recreates the activity. It's what other answers have also tried to achieve.. i.e. it's a workaround by predefining themes it's not programmatically or dynamically creating themes.
    – frezq
    Jun 25, 2020 at 18:33
  • 1
    OK, I will add your link in the post...
    – IQ.feature
    Mar 27, 2022 at 2:47
3

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

if (dark_ui) {
    this.setTheme(R.style.Theme_Dark);

    if (Build.VERSION.SDK_INT >= 21) {
        getWindow().setNavigationBarColor(getResources().getColor(R.color.Theme_Dark_primary));
        getWindow().setStatusBarColor(getResources().getColor(R.color.Theme_Dark_primary_dark));
    }
} else {
    this.setTheme(R.style.Theme_Light);
}

setContentView(R.layout.activity_main);

toolbar = (Toolbar) findViewById(R.id.app_bar);

if(dark_ui) {
    toolbar.setBackgroundColor(getResources().getColor(R.color.Theme_Dark_primary));
}
3
  • add this code: android:background="?attr/colorPrimary", to your toolbar (in the .xml file), so you don't need to set the background in java. Apr 22, 2015 at 17:57
  • But I have two different Toolbars, one for a light theme an another for a dark theme. If I add the android:background="?attr/colorPrimary" I have to use some kind of selector.
    – lgallard
    May 19, 2015 at 13:27
  • I had a lot themes and I only use that code. Take a look to this app: play.google.com/store/apps/… May 19, 2015 at 13:42
1

from an activity you can do:

getWindow().setStatusBarColor(i color);
1
  • 3
    Funny that this answer has -8 votes but solves my problem :D Jul 20, 2017 at 17:00
1

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

enter image description here

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

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>

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

and inside the activity set theme

 setTheme(R.style.AppTheme_NewTheme);
 setContentView(R.layout.activity_main);
3
  • I see that there are already earlier answers that describe switching styles. Under what situation is your answer more appropriate than those? And to be clear, the question says "At runtime, the user decides he wants to use #ccffff as a primary color. Of course there's no way I can create themes for all possible colors." This doesn't solve that need; however if no one had described how to do this, it would be useful to know. Nov 29, 2019 at 21:28
  • @ToolmakerSteve Did you get any solution
    – sejn
    Oct 30, 2020 at 4:37
  • @sejn - you do something similar to this answer - and then you must remove (pop from nav stack) whatever is showing on screen, and push a new instance of it again - to force "inflate" to happen again, creating a new view with revised theme. Exact details depend on whether you are using fragments, and can easily replace the current one, or instead must re-start the current activity. Google elsewhere for help with that step, or post a new question describing what you need to do - reference this Q&A, explain the step you have not solved. Oct 30, 2020 at 18:37
-2

USE A TOOLBAR

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

package view;

import android.app.Activity;
import android.content.Context;
import android.graphics.ColorFilter;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.support.v7.internal.view.menu.ActionMenuItemView;
import android.support.v7.widget.ActionMenuView;
import android.support.v7.widget.Toolbar;
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) {
        super(context);
        // TODO Auto-generated constructor stub
        ctxt = context;
    }

    int itemColor;
    Context ctxt;

    @Override 
    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.
        toolbarView.setTitleTextColor(toolbarIconsColor);
        toolbarView.setSubtitleTextColor(toolbarIconsColor);
    }

    public static void doColorizing(View v, final ColorFilter colorFilter, int toolbarIconsColor){
        if(v instanceof ImageButton) {
            ((ImageButton)v).getDrawable().setAlpha(255);
            ((ImageButton)v).getDrawable().setColorFilter(colorFilter);
        }

        if(v instanceof ImageView) {
            ((ImageView)v).getDrawable().setAlpha(255);
            ((ImageView)v).getDrawable().setColorFilter(colorFilter);
        }

        if(v instanceof AutoCompleteTextView) {
            ((AutoCompleteTextView)v).setTextColor(toolbarIconsColor);
        }

        if(v instanceof TextView) {
            ((TextView)v).setTextColor(toolbarIconsColor);
        }

        if(v instanceof EditText) {
            ((EditText)v).setTextColor(toolbarIconsColor);
        }

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

//                              innerView.post(new 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

toolbar.setItemColor(Color.Red);

Sources:

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

6
  • This does not answer the question. Especially the part "My goal is to eventually have the ActionBar and all widgets like a CheckBox to use this primary color.".
    – nhaarman
    May 21, 2015 at 8:23
  • Then just add on to include a checkbox. For example, add if (v instanceof CheckBox) {themeChexnoxWithColor(toolbarIconsColor) ; I don't see how this doesn't answer your question honestly May 21, 2015 at 12:48
  • @nhaarman you can dynamically set the actionbar color like this stackoverflow.com/questions/23708637/change-actionbar-background-color-dynamically I just don't exactly understand your question May 21, 2015 at 12:59
  • I have an app where the user can choose the actionbar color and actionbar item colors. I don't see what else you need May 21, 2015 at 13:00
  • 2
    This was very helpful to me.
    – Firefly
    Jul 13, 2015 at 16:16
-6

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="http://schemas.android.com/apk/res/android" >
    <solid android:color="?attr/colorPrimary"/>
</shape>

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.