我有一个kotlin类,它扩展了LinearLayouts。我用它为布局添加半径。这是课程。
import android.content.Context
import android.graphics.Canvas
import android.graphics.Path
import android.graphics.RectF
import android.util.AttributeSet
import android.widget.LinearLayout
class RadiusLinearLayout(context: Context, attrs: AttributeSet) : LinearLayout(context, attrs) {
private lateinit var rectF: RectF
private val path = Path()
private var cornerRadius = 25f
init {
val radiusAttribute = getContext().obtainStyledAttributes(attrs, R.styleable.RadiusLinearLayout)
cornerRadius = radiusAttribute.getFloat(R.styleable.RadiusLinearLayout_cornerRadius, 25f)
radiusAttribute.recycle()
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
rectF = RectF(0f, 0f, w.toFloat(), h.toFloat())
resetPath()
}
override fun draw(canvas: Canvas) {
val save = canvas.save()
canvas.clipPath(path)
super.draw(canvas)
canvas.restoreToCount(save)
}
override fun dispatchDraw(canvas: Canvas) {
val save = canvas.save()
canvas.clipPath(path)
super.dispatchDraw(canvas)
canvas.restoreToCount(save)
}
private fun resetPath() {
path.reset()
path.addRoundRect(rectF, this.cornerRadius, this.cornerRadius, Path.Direction.CW)
path.close()
}
}
我还有一个styleable.xml文件,用于在xml布局文件上定义时设置布局的半径
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="RadiusLinearLayout">
<attr name="cornerRadius" format="float"/>
</declare-styleable>
</resources>
这是一个例子。
<test.com.RadiusLinearLayout
android:id="@+id/containerLinearLayoutCF"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cornerRadius="25"
android:orientation="vertical"/>
我想使用dp而不是float值来设置布局的半径,怎么办?