最近作了一个单个LottieAnimationView根据用户点击选项的不一样,加载不一样的lottie动画的需求。网上的一些demo和博客大多只是单独的加载一个lottie动画,广泛不会有问题,可是若是加载不一样的lottie动画时,遇到了一些问题,踩了一些坑,好比lottie动画只能播放第一个,后面的就不放了,好比第二个lottie动画播放时会闪一下第一个lottie动画画面,好比播放混乱,明明点击的是第一个动画,播放的确实第二个等等。特此把最后的使用总结以下。最后的效果由于涉及内部内容就不放了。json
/**
* 播放sdcard的动画
* @param jsonFile json文件
* @param imagesDir json文件引用的image文件的目录
* @throws Exception
*/
private void showSdcardLottieEffects(File jsonFile,File imagesDir) throws Exception{
BufferedReader bufferedReader = new BufferedReader(new FileReader(jsonFile));
String content = null;
StringBuilder stringBuilder = new StringBuilder();
while ((content = bufferedReader.readLine()) != null){
stringBuilder.append(content);
}
JSONObject jsonObject = new JSONObject(stringBuilder.toString());
final String absolutePath = imagesDir.getAbsolutePath();
//提供一个代理接口从 SD 卡读取 images 下的图片
specialEffectLottieAnim.setImageAssetDelegate(new ImageAssetDelegate() {
@Override
public Bitmap fetchBitmap(LottieImageAsset asset) {
Bitmap bitmap = null;
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(absolutePath + File.separator + asset.getFileName());
bitmap = BitmapFactory.decodeStream(fileInputStream);
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if (bitmap == null) {
bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ALPHA_8);
}
if (fileInputStream != null) {
fileInputStream.close();
}
} catch (IOException e) {
LogUtil.e(TAG, e);
}
}
return bitmap;
}
});
LottieComposition.Factory.fromJson(getResources(), jsonObject, new OnCompositionLoadedListener() {
@Override
public void onCompositionLoaded(@Nullable LottieComposition composition) {
if(composition == null){
return;
}
specialEffectLottieAnim.cancelAnimation();
specialEffectLottieAnim.setProgress(0);
specialEffectLottieAnim.setComposition(composition);
specialEffectLottieAnim.playAnimation();
specialEffectLottieAnim.setVisibility(View.VISIBLE);
}
});
}
复制代码
/**
* 从本地查找lottie动画
* @param interactCode 特效name
*/
private void showLocalLottieEffects(String interactCode){
LogUtil.i(TAG, "启动本地动画 folderIsWatch:"+ folderIsWatch+ " interactCode:"+interactCode);
try{
//json文件的路径根据具体需求修改
LottieComposition composition = LottieComposition.Factory.fromFileSync(this, "lottie/" +interactCode+".json");
specialEffectLottieAnim.cancelAnimation();
specialEffectLottieAnim.setProgress(0);
specialEffectLottieAnim.setComposition(composition);
specialEffectLottieAnim.playAnimation();
specialEffectLottieAnim.setVisibility(View.VISIBLE);
}catch (Exception e){
LogUtil.i(TAG, "启动本地动画 "+" interactCode:"+interactCode+"出错",e);
}
}
复制代码