Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically change the primary color in Android L?

Is there a way to change programmatically the primary colors. I would like to do it in code depending on the screen/state of the app.

Currently I can only set the colors in the theme (static) :

<item name="android:colorPrimary">@color/primary_color</item>
<item name="android:colorPrimaryDark">@color/dark_color</item>
<item name="android:colorBackground">@android:color/white</item>
<item name="android:colorAccent">@color/primary_color</item>
<item name="android:colorControlHighlight">@color/primary_color</item>
like image 833
ebtokyo Avatar asked Aug 17 '14 23:08

ebtokyo


People also ask

How do I change the color scheme in Android Studio?

To change default themes go to File and click on Settings. A new Settings dialog will appear, like this. Under the Appearance & Behaviour -> Appearance, you will find Theme. Choose the right theme from the drop-down and click on Apply and then Ok.


Video Answer


2 Answers

You can, of course, implement custom subclasses of View that have methods for setting colors.

You can also define multiple themes with you various color schemes.

Views look up theme information from the context when they are created. So to change the styles applied from a theme you will have to recreate your view hierarchy with a context that uses the right theme.

One way to do that, is to create a new ContextThemeWrapper and then get a LayoutInflator that uses that theme wrapper, remove the old version of your layout and re-inflate your layout.

Roughly:

ContextThemeWrapper themeWrapper = new ContextThemeWrapper(this, R.style.AppThemeWithColorScheme2);
LayoutInflater layoutInflater = LayoutInflater.from(themeWrapper);
viewContainer.removeAllViews();
layoutInflater.inflate(R.layout.my_layout, viewContainer, true );

If you are using Action Bar, that may be a bit more tricky, because the Action Bar is created once per activity.

like image 142
yogurtearl Avatar answered Sep 22 '22 17:09

yogurtearl


USe this code for setting toolbarcolor and status bar (darker toolbar color)

toolbar.setBackgroundColor(toolbarColor);
factor=0.8f; 
int a = Color.alpha(toolbarcolor);
int r = Math.round(Color.red(toolbarcolor) * factor);
int g = Math.round(Color.green(toolbarcolor) * factor);
int b = Math.round(Color.blue(toolbarcolor) * factor);
int statusColor=Color.argb(a,
        Math.min(r, 255),
        Math.min(g, 255),
        Math.min(b, 255));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    Window window = MainActivity.this.getWindow();
    window.setStatusBarColor(statusColor);
}
like image 29
Vaishali Malviya Avatar answered Sep 24 '22 17:09

Vaishali Malviya