如果你有一个视图,如TextView,需要设置背景和边框,你可以使用以下Kotlin代码实现:
val view = findViewById(R.id.miTextView) as TextView
val borderColor : Int = Color.GRAY,
val backgroundColor : Int = Color.GRAY,
val borderWidth : Float = 5F,
val borderRadius : Float = 15F
val borderShape = ShapeDrawable().apply {
shape = RoundRectShape(floatArrayOf(borderRadius, borderRadius, borderRadius, borderRadius, borderRadius, borderRadius, borderRadius, borderRadius), null, null)
paint.color = borderColor
paint.style = Paint.Style.STROKE;
paint.strokeWidth = borderWidth;
}
val backgroundShape = ShapeDrawable().apply {
shape = RoundRectShape(floatArrayOf(borderRadius, borderRadius, borderRadius, borderRadius, borderRadius, borderRadius, borderRadius, borderRadius), null, null)
paint.color = backgroundColor
paint.style = Paint.Style.FILL_AND_STROKE;
}
val composite = LayerDrawable(arrayOf<Drawable>(backgroundShape, borderShape))
view.background = composite