需求:
最近需要实现应用内多主题的需求: 要求应用内预置 10 个左右的主题配色方案, 用户可按需切换.
刚一拿到需求, 觉得这简单, 用 Android 的 theme + style 就可以搞定了. 没过多久就遇到了 attr 无法被 selector, drawable 等 xml 资源引用的大坑.
主题色切换的方案中文网络上一搜一大堆, 但没有哪位博主好心的提起这里还有这么深一个坑的…
这里先把解决方案简要叙述一下.
Android 预置多主题解决方案:
首先定义主题配色相关属性, 我将之单独写在 values/style_themes_attrs.xml 里.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="color_bkg_main" format="color" />
<attr name="color_action_bar" format="color" />
<attr name="color_action_bar_text" format="color" />
<attr name="color_primary" format="color" />
<attr name="color_primary_pressed" format="color" />
<attr name="color_primary_disabled" format="color" />
<attr name="color_text" format="color" />
<attr name="color_text_pressed" format="color" />
<attr name="color_text_disabled" format="color" />
<attr name="color_text_sub" format="color" />
<attr name="color_text_hint" format="color" />
<attr name="color_divider" format="color" />
</resources>
这些属性是应用全局的, 为便于引用, 不应该写在 <declare-styleable>
标签里.
然后定义各个主题配色的具体颜色值 (即给以上属性赋值), 我将之单独写在 values/style_themes.xml 里.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="theme_default" parent="BaseAppTheme">
<item name="color_bkg_main">#f1f1f1</item>
<item name="color_action_bar">#ee9c18</item>
<item name="color_action_bar_text">#fff</item>
<item name="color_primary">#ee9c18</item>
<item name="color_primary_pressed">#80ee9c18</item>
<item name="color_primary_disabled">#666</item>
<item name="color_text">#202020</item>
<item name="color_text_pressed">#80202020</item>
<item name="color_text_disabled">#666</item>
<item name="color_text_sub">#717171</item>
<item name="color_text_hint">#b6b6b6</item>
<item name="color_divider">#e2e2e2</item>
</style>
<style name="theme_sky" parent="theme_default">
<item name="color_action_bar">#02a8f3</item>
<item name="color_primary">#02a8f3<