我们知道,我们可以使用selector的xml文件来定义多种状态的颜色或图片,它们被存放在res/color和res/drawable目录下。如果你在Java或Kotlin代码中,直接使用R.drawable.selector_xxx,会有效果吗?答案是否定的。
我们如果要在代码中使用多种状态的shape或color,则需要使用StateListDrawable和ColorStateList类。
StateListDrawable
val stateListDrawable = StateListDrawable()
val disableDrawable = GradientDrawable()
val hoverDrawable = GradientDrawable()
val normalDrawable = GradientDrawable()
disableDrawable.cornerRadius = cornerRadius
hoverDrawable.cornerRadius = cornerRadius
normalDrawable.cornerRadius = cornerRadius
disableDrawable.setColor(disableBgColor)
hoverDrawable.setColor(hoverBgColor)
normalDrawable.setColor(normalBgColor)
stateListDrawable.addState(intArrayOf(-android.R.attr.state_enabled), disableDrawable)
stateListDrawable.addState(intArrayOf(android.R.attr.state_pressed), hoverDrawable)
stateListDrawable.addState(IntArray(0), normalDrawable)
return stateListDrawable
-代表state的取值为false,没有带-的代表state的取值为true,不传代表normal状态。
ColorStateList
val colorStateList = ColorStateList(
arrayOf(intArrayOf(android.R.attr.state_pressed), IntArray(0)),
intArrayOf(R.color.black, R.color.white)
)