针对自定义及动态创建View的换肤实践

本文介绍了如何在单Activity+多Fragment的项目中,利用LayoutInflater.Factory接口实现定制换肤功能。着重讲解了如何处理Activity、Fragment、系统及自定义View的换肤逻辑,以及如何通过自定义资源管理确保在黑夜模式下的快速切换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、背景

公司的业务需要使用换肤功能实现白天/黑夜模式,调研了市场主流换肤框架,主要采用了LayoutInflater.Factory接口干涉Xml中View解析的过程,将创建View的过程由自己来接手。但本项目大量使用自定义View及动态创建View,Xml中描述界面的情况不多,针对这种情况,我设计了一套轻量级的实时换肤框架。

二、使用

项目UI框架是单Activity+多Fragment的结构,为满足实时刷新,不出现页面闪烁的需求,所以从三个方面来实现换肤功能。

1.Activity

当前项目中需要实时刷新的Activity只有首页和设置页,所以单独对这两个Activity进行处理。首先需要实现Skinable接口,在页面创建和销毁时添加监听,这样,主题发生改变时,就会通知到applySkin()方法。

class MainActivity : RootActivity(), MainContract.View, Skinable {
    ...
    private fun initView() {
        SkinManager.instance.register(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        SkinManager.instance.unregister(this)
    }

    override fun applySkin() {
        container.setBackgroundColor(resources.getColor(R.color.bg_color_primary))
        navigation.setBackgroundColor(resources.getColor(R.color.bg_color_primary))
        for (fragment in supportFragmentManager.fragments) {
            if (fragment is RootFragment && fragment.isAdded && !fragment.isDetached) {
                fragment.refreshStatusBar()
                if (fragment is Skinable) {
                    fragment.applySkin()
                }
            }
        }
        changeStatusBarTheme()
    }
    ...
}
2.Fragment

Fragment是UI界面的承载体,所以在RootFragment中实现了Skinable接口,所有的Fragment需要覆写applySkin()方法,在里面处理自己的换肤逻辑,即设置页面控件的颜色属性(如背景色、字体颜色、图标等)。

3.View

View是每个页面最基础的元素,出于方便使用和易维护的角度,对这层当中的自定义控件和系统控件做了区别处理。

系统控件

直接在Fragment的applySkin()里调用设置相关属性的方法。

showQrCode.background = resources.getDrawable(R.drawable.selector_with_ripple)
addEnigma.setTextColor(resources.getColor(R.color.text_color_tips))

自定义控件

对于自定义控件,直接让控件实现Skinable接口,在自定义控件内部处理控件自己的换肤逻辑,这样外部不用考虑内部控件的逻辑,只需在 Fragment的applySkin()方法中直接调用该自定义控件的applySkin()方法。

class PasswordEditText: AppCompatEditText, Skinable {
    ...
    override fun applySkin() {
        mTextPaint.color = resources.getColor(R.color.text_color_input_hint)
        background = resources.getDrawable(R.drawable.selector_login_edit_bkg)
        setTextColor(resources.getColor(R.color.text_color_minor))
        setHintTextColor(resources.getColor(R.color.text_color_input_hint))
    }
    ...
}
4.资源定义

这里拿黑夜模式进行举例

添加资源目录

首先需要在build.gralde文件的android节点中添加res-nigit

android {
    ...
    sourceSets {
        main {
            res.srcDirs = ['src/main/res', 'src/main/res-night']
        }
        ...
    }
}

定义资源名

黑夜模式的资源需要在res_night中加入同名的_night后缀,如果未添加,默认会取白天模式的。

drawable.png

colors.xml也需要这样定义。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary_night">#333333</color>
    <color name="colorPrimaryDark_night">#00574B</color>
    <color name="colorAccent_night">#26B36D</color>

    <!-- text colors -->
    <color name="text_color_primary_night">#ffffff</color>
    <color name="text_color_minor_night">#cccccc</color>
    <color name="text_color_tips_night">#909399</color>
    ...

    <!-- background colors -->
    <color name="bg_color_primary_night">#333333</color>>
    <color name="bg_color_pressed_night">#2d2d2d</color>
    ...

    <!-- default avatar colors -->
    <color name="default_avatar_red_night">#ED4E4E</color>
    <color name="default_avatar_blue_night">#6C9DD9</color>
    ...

    <!-- bottom sheet colors -->
    <color name="colorSheetText_night">#DE000000</color>
    <color name="colorSheetTitle_night">#8A000000</color>
    <color name="colorSheetDivider_night">#3f717171</color>
    <color name="bg_color_status_bar_night">#333333</color>
</resources>

在这里,推荐大家如果使用图标,最好用SVG图,除了占用空间小、缩放无质量损失以外,添加对于黑夜模式的时候,也只需要修改SVG文件色值即可达到。

三、原理

其实核心思想上面也提到了,就是继承Resource,覆写了getColor()getDrawable()方法。

class CustomResources(val resources: Resources) :
    Resources(resources.assets, resources.displayMetrics, resources.configuration) {

    override fun getColor(id: Int): Int {
        return SkinManager.instance.getColor(id)
    }

    override fun getDrawable(id: Int): Drawable {
        return SkinManager.instance.getDrawable(id)
    }

    fun updateConfig(config: Configuration?, metrics: DisplayMetrics?) {
        resources.updateConfiguration(config, metrics)
    }
}

然后在SkinManager中通过SkinResources获取相应主题的资源。

class SkinResources {
    ...
    fun getSkinColor(context: Context, id:Int): Int {
        val resources = context.resources
        val type = resources.getResourceTypeName(id)
        val color = resources.getResourceEntryName(id)
        val identifier = getIdentifier(context, nameConvert(color), type)
        return when {
            identifier != 0 -> resources.getColor(identifier)
            else -> resources.getColor(id)
        }
    }

    fun getSkinDrawable(context:Context,id:Int): Drawable {
        val resources = context.resources
        val type = resources.getResourceTypeName(id)
        val drawable = resources.getResourceEntryName(id)
        val identifier = getIdentifier(context, nameConvert(drawable), type)
        return when {
            identifier != 0 -> resources.getDrawable(identifier)
            else ->resources.getDrawable(id)
        }
    }
    ...
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值