Android animation reduce stutter/choppy/lag
I've reduced the amount of stutter on my animations by following these rules listed in order of importance when reducing stutter:
- Don't initiate animations in
onCreate
,onStart
oronResume
. - Initiate animations on user events such as
onClick
and disable touch events until animation is complete. - Don't initiate more than 2 animations simultaneously.
If you are using animation you should follow the android docs; in fact in some cases, you might need to postpone your fragment transition for a short period of time. For example in my case I need to postpone my animation until my viewmodel return some data:
Use postponeEnterTransition()
in the entering fragment onViewCreated()
method:
public class A extends Fragment { @Override public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { ... postponeEnterTransition(); }}
Once the data are ready to start the transition, call startPostponedEnterTransition()
public class A extends Fragment { @Override public void onViewCreated(@NonNull View view, Bundle savedInstanceState) { postponeEnterTransition(); final ViewGroup parentView = (ViewGroup) view.getParent(); // Wait for the data to load viewModel.getData() .observe(getViewLifecycleOwner(), new Observer<List<String>>() { @Override public void onChanged(List<String> list) { // Set the data on the RecyclerView adapter adapter.setData(list); // Start the transition once all views have been // measured and laid out parentView.getViewTreeObserver() .addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { parentView.getViewTreeObserver() .removeOnPreDrawListener(this); startPostponedEnterTransition(); return true; }); } }); }}