问题描述
我正在Android应用中动态地使用主题,如下所示:
I am using themes (dynamically) in my android app, like this:
my_layout.xml (摘录):
<TextView
android:id="@+id/myItem"
style="?my_item_style" />
attrs.xml (摘录):
<attr name="my_item_style" format="reference" />
themes.xml (摘录):
<style name="MainTheme.Blue">
<item name="my_item_style">@style/my_item_style_blue</item>
</style>
<style name="MainTheme.Green">
<item name="my_item_style">@style/my_item_style_green<item>
</style>
styles.xml (摘录):
<style name="my_item_style_blue">
<item name="android:textColor">@color/my_blue</item>
</style>
<style name="my_item_style_green">
<item name="android:textColor">@color/my_blue</item>
</style>
因此,如您所见,我正在动态设置主题.我正在使用此类:
So, as you can see, I am setting themes dynamically. I am using this class:
public class ThemeUtils {
private static int sTheme;
public final static int THEME_BLUE = 1;
public final static int THEME_GREEN = 2;
public static void changeToTheme(MainActivity activity, int theme) {
sTheme = theme;
activity.startActivity(new Intent(activity, MyActivity.class));
}
public static void onActivityCreateSetTheme(Activity activity)
{
switch (sTheme)
{
default:
case THEME_DEFAULT:
case THEME_BLUE:
activity.setTheme(R.style.MainTheme_Blue);
break;
case THEME_GREEN:
activity.setTheme(R.style.MainTheme_Green);
break;
}
}
}
我想知道的是,有什么方法可以在代码中执行此操作(更改主题颜色)?例如,我有以下代码(提取):
What I want to know, is there a way how to do this (change theme color) in code? For example, I have following code (extract):
((TextView) findViewById(R.id.myItem)).setTextColor(R.color.blue);
可以通过一些辅助方法来完成,该方法将对可用主题使用switch
命令,并为主题返回正确的颜色.但是我想知道是否有更好,更好和更快的方法.
It can be done by some helper method, which would use switch
command for available themes and return correct color for a theme. But I would like to know if there is some better, nicer and faster way.
谢谢!
推荐答案
我终于使用以下方法完成了此操作:
I have finally done it using following method:
public static int getColor(String colorName) {
Context ctx = getContext();
switch (sTheme) {
default:
case THEME_DEFAULT:
return ctx.getResources().getIdentifier("BLUE_" + colorName, "color", ctx.getPackageName());
case THEME_BLUE:
return ctx.getResources().getIdentifier("BLUE_" + colorName, "color", ctx.getPackageName());
case THEME_GREEN:
return ctx.getResources().getIdentifier("GREEN_" + colorName, "color", ctx.getPackageName());
}
}
这会根据我的主题(我使用前缀)返回颜色.
This returns color according to my theme (I used prefixes).
这篇关于动态设置主题颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!