Android 自定义带文字的 ProgressBar

系统的 ProgressBar 没法完成 UI 效果,故进行简单自定义

效果:

系统默认是没有文字的

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class TextProgressBar @JvmOverloads constructor(context: Context, attributeSet: AttributeSet? = null, defAttrStyle: Int = 0) : ProgressBar(context, attributeSet, defAttrStyle) {
var text = "0%"
var mPaint = Paint()
var rect = Rect()

init {
mPaint.color = Color.BLACK
mPaint.textSize = 20f
}

private fun setText(progress:Int) {
val i = progress * 100 / max
this.text = "$i%"
}

override fun setProgress(progress: Int) {
setText(progress)
super.setProgress(progress)
}

override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)

this.mPaint.getTextBounds(this.text, 0, text.length, rect)
var x = width * (progress * 1f / max) - rect.width() - 10
if (x < 0) {
x = 0f
}
val y = height / 2 - rect.centerY()
canvas?.drawText(this.text, x, y.toFloat(), this.mPaint)
}
}

酱紫