1. 程式人生 > >單個LottieAnimationView載入不同的lottie動畫

單個LottieAnimationView載入不同的lottie動畫

需求

最近做了一個單個LottieAnimationView根據使用者點選選項的不同,載入不同的lottie動畫的需求。網上的一些demo和部落格大多隻是單獨的載入一個lottie動畫,普遍不會有問題,但是如果載入不同的lottie動畫時,遇到了一些問題,踩了一些坑,比如lottie動畫只能播放第一個,後面的就不放了,比如第二個lottie動畫播放時會閃一下第一個lottie動畫畫面,比如播放混亂,明明點選的是第一個動畫,播放的確實第二個等等。特此把最後的使用總結如下。最後的效果因為涉及內部內容就不放了。

載入sdcard的lottie動畫

 /**
     * 播放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); } }); } 複製程式碼

載入應用內部assets目錄下的lottie檔案

/**
     * 從本地查詢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);
        }
    }
  
複製程式碼