Android开发分享一个带圆角的ConstraintLayout的自定义控件
RoundConstraintLayout
直接上代码:
class RoundConstraintLayout (mContext: Context, attrs: AttributeSet) : ConstraintLayout(mContext,attrs){
private var radiusRound:Int
private var topLeftRadius:Int
private var topRightRadius:Int
private var bottomLeftRadius:Int
private var bottomRightRadius:Int
private var strokeLineWidth:Int
private var strokeLineColor:Int
private var backgroundColor = mutableListOf<Int>()
init {
mContext.obtainStyledAttributes(attrs, R.styleable.RoundConstraintLayout).apply {
radiusRound = getDimensionPixelSize(R.styleable.RoundConstraintLayout_radiusRound, 0)
topLeftRadius = getDimensionPixelSize(R.styleable.RoundConstraintLayout_topLeftRadius, 0)
topRightRadius = getDimensionPixelSize(R.styleable.RoundConstraintLayout_topRightRadius, 0)
bottomLeftRadius = getDimensionPixelSize(R.styleable.RoundConstraintLayout_bottomLeftRadius, 0)
bottomRightRadius = getDimensionPixelSize(R.styleable.RoundConstraintLayout_bottomRightRadius, 0)
strokeLineWidth = getDimensionPixelSize(R.styleable.RoundConstraintLayout_strokeLineWidth, 0)
strokeLineColor = getColor(R.styleable.RoundConstraintLayout_strokeLineColor, 0)
backgroundColor.add(getColor(R.styleable.RoundConstraintLayout_bgColor, mContext.getColors(R.color.c_f6)))
getColor(R.styleable.RoundConstraintLayout_bgColorCenter, 0).let { if(it != 0) backgroundColor.add(it) }
getColor(R.styleable.RoundConstraintLayout_bgColorEnd, 0).let { if(it != 0) backgroundColor.add(it) }
}.recycle()
if(radiusRound != 0){
topLeftRadius = radiusRound
topRightRadius = radiusRound
bottomRightRadius = radiusRound
bottomLeftRadius = radiusRound
}
setStyle()
}
private fun setStyle(orientation: GradientDrawable.Orientation = GradientDrawable.Orientation.LEFT_RIGHT){
BaseShapeUtils.setShape(
this,
backgroundColor.toIntArray(),
orientation = orientation,
corner = floatArrayOf(
topLeftRadius.toFloat(), topLeftRadius.toFloat(),
topRightRadius.toFloat(),topRightRadius.toFloat(),
bottomRightRadius.toFloat(),bottomRightRadius.toFloat(),
bottomLeftRadius.toFloat(),bottomLeftRadius.toFloat()
),
strokeWidth = strokeLineWidth,strokeColor = strokeLineColor
)
}
fun setShape(
bgColor:MutableList<Int>? = null,
radiusRound:Int? = null,
tlRadius:Int? = null,
trRadius:Int? = null,
brRadius:Int? = null,
blRadius:Int? = null,
lineWide:Int? = null,
lineColor:Int? = null,
orientation: GradientDrawable.Orientation = GradientDrawable.Orientation.LEFT_RIGHT
){
bgColor?.let {
backgroundColor.clear()
backgroundColor.addAll(it)
}
radiusRound?.let {
topLeftRadius = it
topRightRadius = it
bottomRightRadius = it
bottomLeftRadius = it
}
tlRadius?.let { topLeftRadius = it }
trRadius?.let { topRightRadius = it }
brRadius?.let { bottomRightRadius = it }
blRadius?.let { bottomLeftRadius = it }
lineWide?.let { strokeLineWidth = it }
lineColor?.let { strokeLineColor = it }
setStyle(orientation)
}
}
定义圆角的ConstraintLayout,可以少写很多shape
有需要完整源码的,可以私信我,我每天都看私信的