用于构建常用drawable
实例的kotlin-dsl
框架,包括shape
、ripple
以及selector
的drawable
实例;顺便也支持创建颜色相关的selector
实例。
在app模块的build.gradle文件的适当位置添加以下代码:
implementation 'cn.numeron:drawable.dsl:1.0.0'
- shape(GradientDrawable)
val gradientDrawable = shape(Shape.RECTANGLE) {
//corners(8f)
corners {
topLeft = 8f
topRight = 8f
}
//padding(8)
padding {
top = 8
bottom = 8
}
//solid(Color.parseColor("#FAF0E6"))
gradient {
startColor = Color.RED
centerColor = Color.GREEN
endColor = Color.BLUE
}
}
- ripple(RippleDrawable)
val rippleDrawable = ripple {
color(Color.WHITE)
//content = AppCompatResources.getDrawable(context, R.drawable.ic_launcher_background)
content {
AppCompatResources.getDrawable(context, R.drawable.ic_launcher_background)!!
}
}
- selector(StateListDrawable)
val stateListDrawable = selector {
// 一种状态
addState(State.PRESSED) {
shape {
corners(8f)
solid(Color.parseColor("#FFA500"))
}
}
// 多种状态的组合,可通过`非`和`加`操合并更多状态
addState(State.SELECTED + !State.ENABLED) {
shape {
corners(8f)
solid(Color.parseColor("#FAF0E6"))
}
}
// 默认状态
defState {
shape {
corners(8f)
solid(Color.parseColor("#FF8C00"))
}
}
}
- colorSelector(ColorStateList)
// 与StateListDrawable相同,可通过操作符组合更多状态
val colorStateList = colorSelector {
addState(!State.ENABLED, Color.GRAY)
addState(State.PRESSED, Color.WHITE)
defState(Color.BLACK)
}