如何以编程方式更改Android L中的原色? [英] How to programmatically change the primary color in Android L?

查看:59
本文介绍了如何以编程方式更改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>

推荐答案

您当然可以实现具有用于设置颜色的方法的View的自定义子类.

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.

一种方法是创建一个新的 ContextThemeWrapper 然后获取一个使用该主题包装器的LayoutInflator,删除旧版本的布局,然后重新为您的布局充气.

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.

大致:

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.

这篇关于如何以编程方式更改Android L中的原色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆