android - 如何让我的进度条动画更流畅?
问题描述
我的进度条是在按下按钮时实现的,进度条会增加。释放按钮时,进度条会重置。现在的进度条看起来非常有问题。我认为这是因为它每秒都会被调用,所以它会像那样跳跃。
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
}
解决方案
我建议使用内置动画实用程序来执行此操作。他们将让您指定您想要的任何总持续时间,并负责计算正确的“滴答”时间和费率。您将获得流畅的更新,而无需进行大量手动工作。
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()
}
})
推荐阅读
- python - 从具有重复键的字典列表中创建具有唯一键的字典列表
- java - 如何创建地图
> 有更多的条件? - excel - 将一系列单元格剪切并粘贴到选定的目标位置
- docker - 我需要在谷歌云平台上使用 containerd 吗?
- javascript - 我正在尝试动态添加多个 tagit 字段,但它不适合我
- javascript - 卸载后未清除 React setTimeout 或组件更新
- python - 如何使用 Python 计算数组特定行中的值
- java - 在spring数据存储库中使用deleteBy自定义方法无法执行删除操作
- java - javax.mail.FolderClosedException: * BYE JavaMail 异常
- mono - 如何在 Debian 9.3 上编译 Mono