如何为从 0 到 100 的加载过程设置动画?

How can I animate the loading process from 0 to 100?

初始屏幕上需要一个视图。

即loading,那里以动画的形式显示从0%到100%的loading。

我正在尝试用下面的方法做,但是这个方法不是很好,请问怎么用小动画做呢?

这是我现在的片段代码:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    for (i in 0..100) {
        binding.loadingView.setText("Loading $i %")
    }
}

还有我的 xml:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <data class="SplashScreenBinding">

        <import type="android.view.View" />

        <variable
            name="viewModel"
            type="com.mandarine.aco.splash.SplashViewModel" />
    </data>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/main_background">

        <ImageView
            android:id="@+id/appImageView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:contentDescription="@string/app_name"
            android:scaleType="center"
            android:src="@drawable/logo" />

        <TextView
            android:id="@+id/loadingView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="66dp"
            android:gravity="center_horizontal"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:text="Loading"
            android:textColor="@android:color/white"
            android:textSize="42px"
            tools:text="Loading 43 %" />
    </RelativeLayout>
</layout>

问:如何使从 0 到 100 的加载过程动画化?

由于现在您只需要一个持续设定持续时间并在屏幕上更新 0 - 100 值的加载动画,您可以使用 ValueAnimator.ofInt

private var valueAnimator: ValueAnimator? = null

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    val targetTextView = // ...
    
    valueAnimator = ValueAnimator.ofInt(0, 100).apply {
        addUpdateListener {
            targetTextView.text = "Loading ${it.animatedValue}%"
        }
        interpolator = LinearInterpolator()
        duration = 2000
        start()
    }
}

// You need to end the animation in case the view is being
// destroyed before the animation has completed
override fun onDestroyView() {
    super.onDestroyView()
    valueAnimator?.end()
    valueAnimator = null
}

您还可以根据需要在 valueAnimator 上调用 pause()cancel()end() 来 pause/cancel/end 动画。