Lottie 是 Airbnb 公司开源的动画库。官方文档是这么介绍的
Lottie for Android, iOS, React Native, and Web
。Lottie is a mobile library for Android and iOS that parsesAdobe After Effects
animations exported asjson
withBodymovin
and renders them natively on mobile and on the web!
很简单就不解释了.
在 Android 上使用
- 在项目的
build.gradle
文件中添加如下内容
dependencies {
...
compile 'com.airbnb.android:lottie:2.5.1'
...
}
如果你使用的 SDK 是 26 以上的版本,可以使用 lottie-android 中最新的版本
dependencies {
implementation 'com.airbnb.android:lottie:2.5.5'
}
Tip:Lottie supports API 16 and above
,仅支持 api 16 及以上版本
- 在
res/raw (lottie_rawRes) or assets/ (lottie_fileName)
中存放json
动画文件,在xml
就可以直接使用了,如下:
<com.airbnb.lottie.LottieAnimationView
android:id="@+id/animation_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
// json 动画在 raw 文件夹下使用
app:lottie_rawRes="@raw/hello_world"
// json动画在 assets 文件夹下使用
app:lottie_fileName="hello_world.json"
// Loop indefinitely 设置无限循环
app:lottie_loop="true"
// Start playing as soon as the animation is loaded 自动马上加载
app:lottie_autoPlay="true" />
- 如果你不想用
xml
实现,可以通过代码来实现,实现方式如下:
LottieAnimationView animationView = ...
// json 动画在 raw 文件夹下使用
animationView.setAnimation(R.raw.hello_world);
// or json动画在 assets 文件夹下使用
animationView.setAnimation(R.raw.hello_world.json);
animationView.playAnimation();
- 如果不想本地存放动画文件,可以
从网络读取动画文件
,下面是官方文档的使用介绍,但是不全。可以参考这篇文章的使用方式—-Lottie- 让Android动画实现更简单
JsonReader jsonReader= new JsonReader(new StringReader(json.toString()))
animationView.setAnimation(jsonReader)
animationView.playAnimation
- 使用
LottieComposition
去预加载动画
LottieAnimationView animationView = ...;
...
Cancellable compositionLoader = LottieComposition.Factory.fromJsonString(getResources(), jsonString, (composition) -> {
animationView.setComposition(composition);
animationView.playAnimation();
});
// Cancel to stop asynchronous loading of composition
// compositionCancellable.cancel();
- 动画监听
animationView.addAnimatorUpdateListener((animation) -> {
// Do something.
});
animationView.playAnimation();
...
if (animationView.isAnimating()) {
// Do something.
}
...
animationView.setProgress(0.5f);
...
- 定制动画速度和时常
// Custom animation speed or duration.
ValueAnimator animator = ValueAnimator.ofFloat(0f, 1f);
animator.addUpdateListener(animation -> {
animationView.setProgress(animation.getAnimatedValue());
});
animator.start();
- 循环播放
可以使用setRepeatMode(...)
orsetRepeatCount(...)
控制循环播放,或者你直接在xml
中使用lottie_loop="true"
更多详细使用请参考官方文档
你可以直接下载 lottiefiles 里面的动画 直接使用