如何在Android中实现类似Waze的带进度触发功能的按钮
实现Waze风格带边框进度按钮方案
核心思路是通过PathMeasure计算带圆角矩形边框的完整路径长度,按进度比例截取对应长度的路径绘制,天然解决圆角适配和进度速度不均的问题,具体实现步骤如下:
- 第一步:自定义View继承
AppCompatButton,在构造方法中初始化所需属性和工具类
class ProgressBorderButton @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : AppCompatButton(context, attrs, defStyleAttr) { // 边框宽度、圆角、进度色等可自定义属性 private var strokeWidth = 4f private var radius = 16f private var progressColor = Color.BLUE var progress = 0f set(value) { field = value.coerceIn(0f, 1f) invalidate() } private lateinit var progressPaint: Paint private val borderPath = Path() private val progressPath = Path() private val pathMeasure = PathMeasure() private var totalPathLength = 0f init { initAttrs(attrs) initPaint() } private fun initAttrs(attrs: AttributeSet?) { attrs ?: return val typedArray = context.obtainStyledAttributes(attrs, R.styleable.ProgressBorderButton) strokeWidth = typedArray.getDimension(R.styleable.ProgressBorderButton_strokeWidth, strokeWidth) radius = typedArray.getDimension(R.styleable.ProgressBorderButton_radius, radius) progressColor = typedArray.getColor(R.styleable.ProgressBorderButton_progressColor, progressColor) typedArray.recycle() } private fun initPaint() { progressPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE strokeWidth = this@ProgressBorderButton.strokeWidth color = progressColor strokeCap = Paint.Cap.ROUND } } }
- 第二步:在
onSizeChanged回调中构建完整的带圆角边框路径,计算总路径长度
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) // 缩进半格边框宽度避免绘制时边框被截断 val inset = strokeWidth / 2f val drawRect = RectF(inset, inset, w - inset, h - inset) borderPath.reset() // 可自由调整圆角值,哪怕设置为高度的一半做胶囊型按钮也完全适配 borderPath.addRoundRect(drawRect, radius, radius, Path.Direction.CW) pathMeasure.setPath(borderPath, false) totalPathLength = pathMeasure.length }
- 第三步:重写
onDraw方法绘制对应进度的边框
override fun onDraw(canvas: Canvas) { super.onDraw(canvas) if (progress <= 0f) return progressPath.reset() // 按进度比例截取路径 val stop = totalPathLength * progress pathMeasure.getSegment(0f, stop, progressPath, true) canvas.drawPath(progressPath, progressPaint) }
- 第四步:封装倒计时启动方法,进度完成自动触发点击逻辑
fun startCountdown(durationMs: Long) { progress = 0f ValueAnimator.ofFloat(0f, 1f).apply { duration = durationMs interpolator = LinearInterpolator() addUpdateListener { animator -> progress = animator.animatedValue as Float } addListener(object : Animator.AnimatorListener { override fun onAnimationEnd(animation: Animator?) { // 进度走完自动触发按钮点击事件 performClick() } override fun onAnimationStart(animation: Animator?) = Unit override fun onAnimationCancel(animation: Animator?) = Unit override fun onAnimationRepeat(animation: Animator?) = Unit }) start() } }
方案优势
- 圆角可任意调整:路径构建时直接传入自定义圆角值即可,不存在圆角适配问题
- 进度速度完全均匀:通过路径总长度比例计算进度,圆角部分的长度也会纳入总长度统计,配合线性插值器可实现全路径匀速动画,不会出现边和角进度速度不一致的问题
内容的提问来源于stack exchange,提问作者Emil Adz
相关产品推荐
相关产品推荐

