1

ColorStateList 与 StateListDrawable

 2 years ago
source link: http://i.lckiss.com/?p=7915
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

ColorStateList 与 StateListDrawable

2022-04-13

在刚开始写 Android 的时候总是写一些带状态的 xml (Selector) ,而实际工作中往往并不会去使用 Android 提供的那些状态,而是结合业务逻辑去动态指定 state 对应的资源或者颜色或者其他状态变化。

背景是这样的:最近在给一个三方库做扩展,那个库挺老了,在逻辑中发现他在状态处理的时候用了 ColorStateList ,而我要做的是根据状态制定背景,之前仅支持颜色,由于我未能找到什么暴露出来的状态回调,就只能按他以往的逻辑去走了,我在想是否存在类似 StateDrawable 的东西,后来发现确实存在,只是使用上不太相同。

对于代码动态指定带 state 的 color Drawable 的用法:

val background = GradientDrawable()
val states = arrayOf(intArrayOf(android.R.attr.state_selected), intArrayOf())
val colors = intArrayOf(selectedColor, Color.TRANSPARENT)
val colorList = ColorStateList(states, colors)
background.color = colorList
//use 
view.background = background

对于代码动态指定带 state 的 state Drawable 的用法:

val stateListDrawable = StateListDrawable()
stateListDrawable.addState(intArrayOf(android.R.attr.state_selected), selectedDrawable)
stateListDrawable.addState(intArrayOf(), ColorDrawable(ContextCompat.getColor(context, android.R.color.transparent)))
//use 
view.background = stateListDrawable

对比起来,StateListDrawable 比 ColorStateList 更好理解,总之用法就是这样了。 我不怎么用,如果需要了解更多,可以参考官方文档:

https://developer.android.com/reference/android/content/res/ColorStateList

https://developer.android.com/reference/android/graphics/drawable/StateListDrawable


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK