Android中通过SeekBar控制Lottie动画进度的技术问询
用SeekBar控制Lottie动画进度
1. 配置Lottie依赖
先确保项目引入Lottie库,在模块级build.gradle(或build.gradle.kts)中添加依赖:
dependencies { implementation 'com.airbnb.android:lottie:6.4.0' }
2. 编写布局文件
在Activity布局中添加LottieAnimationView和SeekBar,把SeekBar最大值设为100(对应0%-100%进度),同时禁用Lottie自动播放:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp"> <com.airbnb.lottie.LottieAnimationView android:id="@+id/lottie_view" android:layout_width="wrap_content" android:layout_height="wrap_content" app:lottie_fileName="your_animation.json" <!-- 替换成你的Lottie JSON文件名 --> app:lottie_autoPlay="false" app:lottie_loop="false"/> <SeekBar android:id="@+id/progress_seekbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="24dp" android:max="100"/> </LinearLayout>
3. 实现进度控制逻辑
在Activity中绑定控件,给SeekBar添加进度监听,把SeekBar的0-100数值转换成Lottie需要的0.0f-1.0f进度值:
import android.os.Bundle import android.widget.SeekBar import androidx.appcompat.app.AppCompatActivity import com.airbnb.lottie.LottieAnimationView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val lottieView = findViewById<LottieAnimationView>(R.id.lottie_view) val seekBar = findViewById<SeekBar>(R.id.progress_seekbar) // 初始化进度为0 lottieView.progress = 0f // SeekBar进度变化监听 seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) { // 将SeekBar的0-100进度转换为Lottie需要的0.0-1.0比例 val lottieProgress = progress / 100f lottieView.progress = lottieProgress } override fun onStartTrackingTouch(seekBar: SeekBar?) {} override fun onStopTrackingTouch(seekBar: SeekBar?) {} }) } }
关键说明
- Lottie的
progress属性接收0.0f到1.0f的浮点数,对应动画0%到100%进度,所以要把SeekBar的整数进度除以100f做转换。 - 禁用
lottie_autoPlay是为了让动画完全由SeekBar控制,不会自动播放。 - 如果Lottie JSON文件放在
assets目录下,直接用app:lottie_fileName指定文件名即可;如果是远程资源,可调用lottie.setAnimationFromUrl()加载。
内容的提问来源于stack exchange,提问作者hungrycoder
相关产品推荐
相关产品推荐

