使用步骤:
1、添加依赖
implementation 'com.airbnb.android:lottie:$lottieVersion'
2、在xml里写入
<com.airbnb.lottie.LottieAnimationView
android:id="@+id/lottieAnimationView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:lottie_fileName="hello-world.json"
app:lottie_loop="true"
app:lottie_autoPlay="true" />
3、在java代码里使用(加载assets目录下的json文件)
lottieAnimationView = findViewById(R.id.lottieAnimationView);
lottieAnimationView.setImageAssetsFolder("images");
lottieAnimationView.setAnimation("data.json");
lottieAnimationView.loop(true);
lottieAnimationView.playAnimation();
几种常用方式:
1、加载服务器上的json文件
LottieComposition.Factory.fromJson(getResources(), json, new OnCompositionLoadedListener() {
@Override
public void onCompositionLoaded(LottieComposition composition {
lottieAnimationView.setComposition(composition);
lottieAnimationView.playAnimation();
}
});
2、通过url加载服务器上的压缩包
直接加载:
lottieAnimationView.setAnimationFromUrl(url);
lottieAnimationView.playAnimation();
下载到本地指定文件夹再加载:
// 资源zip
public final static File LOTTIE_FILES = new File(Environment.getExternalStorageDirectory()+"/ctclient/lottie/lottie.zip");
// 动效图片资源
public final static File IMAGES_FILES = new File(Environment.getExternalStorageDirectory()+"/ctclient/lottie/images");
// data.json路径
public final static File JSON_FILE = new File(Environment.getExternalStorageDirectory()+"/ctclient/lottie/data.json");
FileInputStream fis = null;
if (JSON_FILE.exists()) {
try {
fis = new FileInputStream(JSON_FILE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
if (fis == null || !IMAGES_FILES.exists()) {
Log.i("huangssh", "动画资源不存在");
return;
}
final String absolutePath = IMAGES_FILES.getAbsolutePath();
// 开启硬件加速
lottieAnimationView.useHardwareAcceleration(true);
// 设置动画文件夹代理类
lottieAnimationView.setImageAssetDelegate(new ImageAssetDelegate() {
@Override
public Bitmap fetchBitmap(LottieImageAsset asset) {
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inScaled = true;
opts.inDensity = UtilPhoneParam.densityDpi;
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeFile(absolutePath + File.separator + asset.getFileName(), opts);
}catch (Exception e){
e.printStackTrace();
}
return bitmap;
}
});
// 设置动画
LottieComposition.Factory.fromInputStream(fis, new OnCompositionLoadedListener() {
@Override
public void onCompositionLoaded(@Nullable LottieComposition composition) {
lottieAnimationView.setComposition(composition);
lottieAnimationView.playAnimation();
}
});
常用方法:
1、监听动画进度
lottieAnimationView.addAnimatorUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
// 判断动画加载结束
if (valueAnimator.getAnimatedFraction() == 1f) {
if (dialog.isShowing() && getActivity() != null)
dialog.dismiss();
}
}
});
播放、暂停、取消
lottieAnimationView.pauseAnimation();
lottieAnimationView.cancelAnimation();
lottieAnimationView.playAnimation();
网友评论