一、前言
在实际开发中,当数据加载时候我们要显示一个圆形旋转当进度条。这个系统提供当有,但是UI给的往往会有些变动,例如如下效果
这时候该怎么做呢?通常网上的做法是继承View进行自己绘制。但是为什么不能继承现有的进度条进行绘制呢?
二、编码
1、拓展带文字的进度条
首先我们选择新版的ContentLoadingProgressBar
来进行继承拓展(因为这个相对于ProgressBar
来说用户体验上会有一点优化)。然后在继承的控件里面绘制文字,然后选择设置进度条的背景色。代码如下:
class CustomProgress: ContentLoadingProgressBar {
//中心显示的文字
private var centerText = "Scanning..."
private var textColor = Color.parseColor("#5ED9ED")
set(value) {
field = value
postInvalidate()
}
//绘制的画笔
private val textPaint = Paint()
constructor(context: Context) : super(context){
initPaint()
}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs){
initPaint()
}
private fun initPaint(){
textPaint.color = textColor
textPaint.textSize = PxUtils.spToPx(12,context).toFloat()
textPaint.style = Paint.Style.FILL
textPaint.isAntiAlias = true
textPaint.textAlign = Paint.Align.CENTER
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvasCenterText(canvas)
}
/**
* 绘制中心的文字
*/
private fun canvasCenterText(canvas: Canvas?){
canvas?.drawText(centerText, (width / 2).toFloat(), (width / 2).toFloat(), textPaint)
}
}
2、创建动画背景
在../app/res/
文件夹下面创建anim
文件夹。创建anim_progress.xml
文件。内容如下:
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="50"
android:drawable="@mipmap/img_processing_ring"
android:fromDegrees="0"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="1080"/><!-- 值越大速度越快 -->
其中动画文件里面的drawable
引用的是一个旋转的图片,也可以自定义。
使用如下:
<com.custom.view.CustomProgress
android:id="@+id/media_progressbar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="200dp"
android:layout_height="200dp"
android:indeterminateDrawable="@anim/anim_progress"
android:visibility="visible"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:visibility="visible"/>