Android 多主题切换 (theme + style) 及 selector/drawable 无法引用 ?attr 属性的问题

本文介绍了Android应用内实现多主题切换的需求及遇到的问题,特别是attr属性无法在selector和drawable中正常引用的问题。文章详细阐述了解决这些问题的步骤,包括预置多主题的实现方式,AppCompatActivity的使用,以及针对Android不同版本的适配策略。同时,指出了在不同Context中获取资源可能导致的问题,并给出相应建议。
摘要由CSDN通过智能技术生成

需求:

最近需要实现应用内多主题的需求: 要求应用内预置 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<
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值