假设我在我的应用程序中定义了两个主题:AppTheme.Blue 和 AppTheme.Green,相应地,我想要一组颜色,因此我可以根据两个不同的主题应用它。
例如,当我在 AppTheme.Green
下调用 ContextCompat.getColor(context, R.color.color_primary);
时,它将返回绿色作为 ?attr/colorPrimary
但如果在 AppTheme.Blue
下则为蓝色,因此小部件将始终与标题栏颜色相同。
我如何定义这两组颜色,系统会根据当前采用的主题动态选择它?
最佳答案
据我了解,您是在谈论使用多个主题。这是您的问题的场景。
在styles.xml中定义两个主题
蓝色主题:
<style name="AppTheme.Blue" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">@color/primaryColor_blue</item>
<item name="colorPrimaryDark">@color/primaryColorDark_blue</item>
<item name="colorAccent">@color/primaryAccent_blue</item>
<item name="backgroundColor">@color/primaryColorDark_blue</item>
</style>
绿色主题:
<style name="AppTheme.Green" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">@color/primaryColor_green</item>
<item name="colorPrimaryDark">@color/primaryColorDark_green</item>
<item name="colorAccent">@color/primaryAccent_green</item>
<item name="backgroundColor">@color/primaryColorDark_green</item>
</style>
相应地定义color.xml中的所有颜色
添加以下代码以获取所选主题的原色并将其设置到您的小部件。
TypedValue typedValue = new TypedValue();
Resources.Theme theme = this.getTheme();
theme.resolveAttribute(android.R.attr.textColorPrimary, typedValue, true);
TypedArray arr =
this.obtainStyledAttributes(typedValue.data, new int[]{
android.R.attr.colorPrimary});
int primaryColor = arr.getColor(0, -1);
yourTextView.setTextColor(primaryColor); //ex
arr.recycle();
如果您选择的主题是蓝色,那么文本颜色也将是蓝色。希望这就足够了。
关于Android多色.xml选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42483730/