最近项目需要用到无重启动态换肤功能,本来打算用github上star最多的 Android-skin-support
但仔细一看发现太复杂而且2年没维护+大量issues没解决,最终放弃
经过探索,发现 Databinding+LiveData 能低成本实现无重启换肤
无重启动态换肤(不需要recreate())无需制作皮肤包无额外依赖(Databinding+LiveData本身几乎开发必备)低侵入性AppCompat和Material组件默认支持(少量属性需要额外支持或适配)自定义View/第三方View 适配过程简单(写个绑定适配器就行了)不需要使用 LayoutInflater.Factory 定义皮肤
以下代码定义了三个皮肤Default,Day,Night,通过调用 AppTheme.update(theme) 就可以完成动态换肤
这里皮肤只支持ColorStateList,因为大部分场景只要 ColorStateList 就够了
如果想要,Drawable/String等各种资源都能支持
data class Theme(
val content: Int,
val background: Int,
)
object Themes {
val Default = Theme(Color.RED, Color.GRAY)
val Day = Theme(Color.BLACK, Color.WHITE)
val Night = Theme(Color.MAGENTA, Color.BLACK)
}
object AppTheme {
val background = MutableLiveData()
val content = MutableLiveData()
init {
update(Themes.Default)
}
fun update(theme: Theme) {
background.value = ColorStateList.valueOf(theme.background)
content.value = ColorStateList.valueOf(theme.content)
}
}
在布局文件中使用皮肤
直接引入AppTheme单例,livedata会关联生命周期,不用担心资源释放
关联生命周期
实际上 Databinding+ObserverableField也能实现无重启换肤,但ObserverableField不能关联生命周期,资源释放麻烦一些
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
// 关联生命周期
binding.lifecycleOwner = this
binding.btnDefault.setonClickListener { AppTheme.update(Themes.Default) }
binding.btnDay.setonClickListener { AppTheme.update(Themes.Day) }
binding.btnNight.setonClickListener { AppTheme.update(Themes.Night) }
}
}
扩展支持的皮肤属性
DataBinding本身已经支持了大量属性,有部分未支持,需要自己实现
实际上就是写个绑定适配器,想要支持第三方控件或自定义控件都差不多,很简单
以下是一些例子
@SuppressLint("RestrictedApi")
@BindingMethods(
BindingMethod(type = ImageView::class, attribute = "tint", method = "setImageTintList")
)
object ThemeAdapter {
@BindingAdapter("background")
@JvmStatic
fun adaptBackground(view: View, value: ColorStateList?) {
view.setBackgroundColor(Color.WHITE)
view.backgroundTintList = value
}
@BindingAdapter("drawableTint")
@JvmStatic
fun adaptDrawableTint(view: TextView, value: ColorStateList?) {
if (view is AppCompatTextView) {
view.supportCompoundDrawablesTintList = value
}
}
@BindingAdapter("android:progressBackgroundTint")
@JvmStatic
fun adaptProgressBackgroundTint(view: SeekBar, value: ColorStateList?) {
view.progressBackgroundTintList = value
}
}
Demo
github.com/czy1121/The…



