Animate ProgressBar update in Android

后端 未结 13 1152
悲哀的现实
悲哀的现实 2020-11-28 04:04

I am using a ProgressBar in my application which I update in onProgressUpdate of an AsyncTask. So far so good.

What I want to do is to animate the prog

相关标签:
13条回答
  • 2020-11-28 04:33

    I just wanted to add an extra value for those who want to use Data Binding with a progress bar animation.

    First create the following binding adapter:

    @BindingAdapter("animatedProgress")
    fun setCustomProgressBar(progressBar: ProgressBar, progress: Int) {
        ObjectAnimator.ofInt(progressBar, "progress", progressBar.progress, progress).apply {
            duration = 500
            interpolator = DecelerateInterpolator()
        }.start()
    }
    

    And then use it in the layout which contains the ViewModel that reports the status updates:

    <ProgressBar
        android:id="@+id/progress_bar_horizontal"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="0dp"
        android:layout_height="30dp"
        android:layout_marginStart="32dp"
        android:layout_marginEnd="32dp"
        android:indeterminate="false"
        android:max="100"
        app:animatedProgress="@{viewModel.progress ?? 0}"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    

    The ViewModel itself will report the status with the following LiveData:

    private val _progress = MutableLiveData<Int?>(null)
    val progress: LiveData<Int?>
        get() = _
    
    0 讨论(0)
提交回复
热议问题