Lottie Android Kotlin 完整指南:安装、方法与实战示例
1. 什么是 Lottie?为什么需要它?
Lottie 是 Airbnb 开源的一款动画库,能够在移动端和网页端实时渲染 After Effects 制作的动画。针对 Android 平台,官方提供了 com.airbnb.android:lottie 库,完美支持 Kotlin 语言。动画设计师通过 Bodymovin 插件将 After Effects 动画导出为 JSON 格式,开发者只需在应用中加载该 JSON 文件,即可实现高质量、小体积的动画渲染。
为什么选择 Lottie?首先,它极大简化了设计师与开发者的协作流程:设计师在熟悉的工具中创作复杂动画,开发者只需引入 JSON 文件即可。其次,Lottie 性能卓越——动画由 GPU 渲染,即使在旧设备上也能保持 60 FPS 的流畅度。最后,Lottie 支持交互控制:你可以控制播放、调整速度、颜色、尺寸,甚至通过代码动态驱动单个图层。
Lottie Android 非常适合以下场景:启动页(Splash Screen)、动态图标、页面转场、手势反馈、UI 微动效等。该库由社区积极维护,LottieFiles 平台还提供了数千个免费动画资源。
2. 安装指南
要在 Kotlin Android 项目中安装 Lottie,请在模块级别的 build.gradle 文件中添加依赖:
dependencies {
implementation 'com.airbnb.android:lottie:6.4.0'
}
如果你使用 Kotlin DSL(build.gradle.kts):
dependencies {
implementation("com.airbnb.android:lottie:6.4.0")
}
同步 Gradle 后即可使用。最低支持的 Android SDK 版本为 21(Android 5.0)。
注意:此库是原生 Android 库,无需使用 pip、npm 或 cargo 等包管理器安装。
3. 快速上手——最小化示例
将动画 JSON 文件(例如 animation.json)放入 app/src/main/res/raw 目录。然后在布局文件中添加 LottieAnimationView:
<!-- activity_main.xml -->
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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">
<com.airbnb.lottie.LottieAnimationView
android:id="@+id/animationView"
android:layout_width="200dp"
android:layout_height="200dp"
app:lottie_rawRes="@raw/animation"
app:lottie_autoPlay="true"
app:lottie_loop="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
在 Activity(或 Fragment)中的 Kotlin 代码:
import android.os.Bundle
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 animationView: LottieAnimationView = findViewById(R.id.animationView)
animationView.playAnimation()
}
}
这个最小化示例会从 raw/animation.json 资源中加载动画,并以无限循环方式播放。