最近UI 一直出现不统一的背景色,不同的圆角,四个角度不同背景描边都不同,我只能不停的去写drawable布局,稍微有点不同就是就去创建不同的drawable,巨烦.所以写了这了一个工具类,永远解决不同UI控件的问题.
不说废话 直接上图:
引用 implementation "com.google.android.material:material:1.3.0"
上代码 代码是用kotlin 顶层方法写的 Java与 kotlin 都可以正常调用
/**
* 控件圆角
* @param Context 上下文
* @param fillColor 填充颜色
* @param stroke 描边宽度
* @param colorRes //描边颜色
* @param allCorner 四边角度
* @param topLeftCorner 左上角
* @param topRightCorner 右上角
* @param bottomRightCorner 左下角
* @param bottomLeftCorner 右下角
*/
@JvmOverloads
fun roundedCorners(activity: Context, fillColor: Int, stroke: Float, colorRes: Int, allCorner: Float,
topLeftCorner: Float = 0f, topRightCorner: Float = 0f, bottomRightCorner: Float = 0f, bottomLeftCorner: Float = 0f): MaterialShapeDrawable {
val shapeAppearanceModel2 = ShapeAppearanceModel.builder().apply {
setAllCorners(RoundedCornerTreatment())
//setAllCornerSizes(allCorner)
setTopLeftCornerSize(if (topLeftCorner == 0f) allCorner else topLeftCorner)
setTopRightCornerSize(if (topRightCorner == 0f) allCorner else topRightCorner)
setBottomRightCornerSize(if (bottomRightCorner == 0f) allCorner else bottomRightCorner)
setBottomLeftCornerSize(if (bottomLeftCorner == 0f) allCorner else bottomLeftCorner)
}.build()
val drawable2: MaterialShapeDrawable = MaterialShapeDrawable(shapeAppearanceModel2).apply {
setTint(ContextCompat.getColor(activity, fillColor)) //填充颜色
paintStyle = Paint.Style.FILL_AND_STROKE
strokeWidth = stroke//描边宽度
strokeColor = ContextCompat.getColorStateList(activity, colorRes)//描边颜色
}
return drawable2
}
kotlin 调用代码:
//四边圆80f
aBinding.background = roundedCorners(this,R.color.colorPrimary,10f,R.color.colorAccent,80f);
//左上边圆80f
bBinding.background = roundedCorners(this,R.color.light_gray,20f,R.color.red_ff4500,0f,80f);
//右上边圆80f
cBinding.background = roundedCorners(this,R.color.red_ff4500,30f,R.color.button_2a73fa,0f,topRightCorner=80f);
//左下边圆80f
dBinding.background = roundedCorners(this,R.color.red_ff4500,5f,R.color.button_2a73fa,0f,bottomRightCorner=80f);
//右下边圆80f
eBinding.background = roundedCorners(this,R.color.colorPrimary,2f,R.color.colorAccent,0f,bottomLeftCorner=80f);
Java 代码调用
Java没有kotlin调用这种多参方便, 没办法指定传那个参数,如果想改变最后一个角就必须把前面的也都传值.
ControlsTheRoundedKt 是顶层方法就是上面的 roundedCorners代码名字
maidian.setBackground(ControlsTheRoundedKt.roundedCorners(this,R.color.colorPrimary,10f,R.color.colorAccent,80f));
maidian.setBackground(ControlsTheRoundedKt.roundedCorners(this,R.color.colorPrimary,10f,R.color.colorAccent,80f,20f));
maidian.setBackground(ControlsTheRoundedKt.roundedCorners(this,R.color.colorPrimary,10f,R.color.colorAccent,80f,20f,10f));
maidian.setBackground(ControlsTheRoundedKt.roundedCorners(this,R.color.colorPrimary,10f,R.color.colorAccent,80f,20f,10f,20f));
maidian.setBackground(ControlsTheRoundedKt.roundedCorners(this,R.color.colorPrimary,10f,R.color.colorAccent,80f,20f,10f,20f,30f));
搞定是不是非常方便,再也不用一直创建drawable写布局了,