为什么我的 Lottie 动画加载这么慢?

Why is my Lottie animation so slow to load?

要说清楚,加载速度慢,而不是动画。

我在 AsyncTask 上使用它如下:

public class GetCurrentLocation extends AsyncTask<String, Void, String>{

private Context mContext;
private View view;

public GetCurrentLocation (View view, Context mContext) {
this.view = view;
this.mContext = mContext;
}


protected void onPreExecute() {
super.onPreExecute();
    //Custom Dialog
    customDialog = new Dialog(mContext);
    customDialog.setContentView(R.layout.dialog_custom);
    customDialog.setTitle("Looking for address");

    //Custom Dialog Animation
    LottieAnimationView animationView = (LottieAnimationView) customDialog.findViewById(R.id.animation_view);
    animationView.setAnimation("PinJump.json"); //Lottie's premade animation
    animationView.loop(true);
    animationView.playAnimation();

    //Custom Dialog Text
    TextView text = (TextView) customDialog.findViewById(R.id.textView);
    text.setText(R.string.dialog_looking_for_address);
    customDialog.show();
}

protected String doInBackground(String... params) {
//Code removed to shorten codeblock, it calls gps location here
return null;
}

protected void onPostExecute(String result) {
super.onPostExecute(result);
customDialog.dismiss();
mPostSolicitationFragment.setLocalText(); //This is the method it transfer the GPS address to the view
}
}

这里一切正常。

我对这段代码的问题是,一旦对话框出现,Lottie 动画需要一秒钟才能出现在屏幕上。如果它在 4G 网络上,我可以看到动画。如果它在 WIFI 上,我唯一能看到的就是文字。

怎样才能让动画一弹出对话框就亮起来?

其实很简单。为了避免出现对话框时渲染合成,我们在LottieComposition中提前渲染,如下图:

        LottieComposition.Factory.fromAssetFileName(mContext, "PinJump.json", new OnCompositionLoadedListener() {
            @Override
            public void onCompositionLoaded(LottieComposition composition) {
                mAnimationView.loop(true);
                mAnimationView.playAnimation();
                TextView text = (TextView) customDialog.findViewById(R.id.textView);
                text.setText(R.string.dialog_looking_for_address);
                customDialog.show();
            }
        });

这样,动画将弹出对话框。