Android Kotlin 自定义圆形 ProgressBar 继承 ProgressBar 实现圆形加载
要实现自定义的圆形加载 ProgressBar,可以继承 ProgressBar 类,并重写 onDraw 方法来绘制圆形加载效果。
首先,在 res/drawable 文件夹下创建一个 xml 文件,命名为 circle_progress.xml,用于设置 ProgressBar 的样式:
<shape
android:shape='ring'
android:thickness='8dp'
android:useLevel='true'>
<solid android:color='@color/colorAccent'/>
</shape>
在自定义的 ProgressBar 类中,重写 onDraw 方法来绘制圆形加载效果:
class CircleProgressBar(context: Context, attrs: AttributeSet) : ProgressBar(context, attrs) {
private val paint: Paint = Paint()
init {
paint.color = Color.BLUE // 设置圆圈的颜色
paint.style = Paint.Style.STROKE // 设置画笔的样式为描边
paint.strokeWidth = 8f // 设置圆圈线条的大小
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
val radius = width / 2f - paint.strokeWidth / 2f // 计算圆圈的半径
val centerX = width / 2f // 圆心的 x 坐标
val centerY = height / 2f // 圆心的 y 坐标
canvas.drawCircle(centerX, centerY, radius, paint) // 绘制圆圈
}
}
使用时,在布局文件中添加 CircleProgressBar:
<com.example.CircleProgressBar
android:layout_width='100dp'
android:layout_height='100dp'
android:indeterminateDrawable='@drawable/circle_progress' />
这样就可以实现一个继承 ProgressBar 的自定义圆形加载 View,并通过设置圆圈线条的大小来控制圆圈的宽度。
原文地址: https://www.cveoy.top/t/topic/nCPD 著作权归作者所有。请勿转载和采集!