How to change programmatically the primary color in Android L

扶醉桌前 提交于 2019-11-28 19:41:40

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.

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

This is most practical with no error, there is no need to do any extra coding, just go to android tree project

res > values > colors then edit these codes:

 <resources>
    <color name="colorPrimary">#008577</color>
    <color name="colorPrimaryDark">#00574B</color>
    <color name="colorAccent">#D81B60</color>
</resources>

add these under style:

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

add into manifest just after ".MainActivity" :

android:theme="@style/AppTheme.NoActionBar">
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!