首页 > 解决方案 > 如何让我的进度条动画更流畅?

问题描述

我的进度条是在按下按钮时实现的,进度条会增加。释放按钮时,进度条会重置。现在的进度条看起来非常有问题。我认为这是因为它每秒都会被调用,所以它会像那样跳跃。

        btn.setOnTouchListener{ view, motionEvent ->
            Toast.makeText(context, "Long click detected", Toast.LENGTH_SHORT).show()
            progressBar.visibility = View.VISIBLE
            var i = 0
            progressBar.progress = i
          val countdownTimer = object: CountDownTimer(5000L, 500L){

               override fun onTick(p0: Long) {
                   Log.d(TAG,"button up")
                   Log.d(TAG, "seconds: $p0")
                   if(motionEvent.action == MotionEvent.ACTION_UP){
                       i = 0
                       this.cancel()
                   }else{
                       i++
                       progressBar.progress = i*100/(5000/1000)
                   }
               }

               override fun onFinish() {
                   Log.d(TAG, "timer finished")
               }
           }.start()
            true
        }

在此处输入图像描述

标签: androidkotlinandroid-progressbar

解决方案


我建议使用内置动画实用程序来执行此操作。他们将让您指定您想要的任何总持续时间,并负责计算正确的“滴答”时间和费率。您将获得流畅的更新,而无需进行大量手动工作。

val animator = ObjectAnimator.ofInt(progressBar, "progress", 0, 100)
animator.interpolator = LinearInterpolator()
animator.duration = 5_000 // milliseconds

btn.setOnTouchListener { _, event ->
    when (event.action) {
        MotionEvent.ACTION_DOWN -> {
            animator.start()
            true
        }
        MotionEvent.ACTION_UP -> {
            animator.cancel()
            progressBar.progress = 0
            true
        }
        else -> false
    }
}

该框架还允许您在进度完成时执行代码(或其他事件,如动画开始时):

animator.addListener(object: AnimatorListenerAdapter() {
    override fun onAnimationEnd(animation: Animator?) {
        Toast.makeText(context, "done", Toast.LENGTH_SHORT).show()
    }
})

推荐阅读