lottie 一个解放双手的动画库
imageimage
Lottie是Airbnb开源的一个支持 Android、iOS 以及 ReactNative,利用json文件的方式快速实现动画效果的库。Android 通过Airbnb的开源项目lottie-android实现,最低支持 API 16;
简单使用
在项目的 build.gradle 文件添加依赖
dependencies {
implementation 'com.airbnb.android:lottie:$lottieVersion'
}
加载src/main/assets里面的lottie_loading.json文件
//代码加载
lottieAnimationView = findViewById(R.id.animation_view);
lottieAnimationView.setImageAssetsFolder("images");
lottieAnimationView.setAnimation("lottie_loading.json");
lottieAnimationView.loop(true);
lottieAnimationView.playAnimation();
//layout布局加载
<com.airbnb.lottie.LottieAnimationView
android:id="@+id/animation_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:lottie_fileName="lottie_loading.json"
app:lottie_loop="true"
app:lottie_autoPlay="true"/>
/**
* 加载网络json文件
* https://assets10.lottiefiles.com/packages/lf20_XOpGZ2.json
* @param url
*/
private void loadUrl(String url) {
Request request;
try {
request = new Request.Builder()
.url(url)
.build();
} catch (IllegalArgumentException e) {
return;
}
if (client == null) {
client = new OkHttpClient();
}
client.newCall(request).enqueue(new Callback() {
@Override public void onFailure(Call call, IOException e) {
}
@SuppressLint("RestrictedApi")
@Override public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) {
}
try {
JSONObject json = new JSONObject(response.body().string());
LottieComposition.fromJson(getResources(), json, new LottieComposition.OnCompositionLoadedListener() {
@Override
public void onCompositionLoaded(LottieComposition composition) {
setComposition(composition);
}
});
} catch (JSONException e) {
}
}
});
}
//开始动画
private void setComposition(LottieComposition composition){
animation_view_network.setProgress(0);
animation_view_network.loop(true);
animation_view_network.setComposition(composition);
animation_view_network.playAnimation();
}
//取消动画
animation_view_network.cancelAnimation();
编译效果
网友评论