Home » Android » android – How to disable/avoid Fragment custom animations after screen rotation

android – How to disable/avoid Fragment custom animations after screen rotation

Posted by: admin June 15, 2020 Leave a comment

Questions:

I have just figured out that every time I setRetainInstance(true) on a Fragment it works as expected (Fragment data is retained), but this is causing the fragment’s custom animation to be executed again after screen rotation.

Is there a way to avoid/disable those animations on screen rotation?

The fragment is created using the following animations:

setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left, R.anim.slide_in_left,
R.anim.slide_out_right);

So, I don’t want those “sliding animations” to be executed again on screen rotation.

How to&Answers:

This is how I handled it

private boolean viewsHaveBeenDestroyed;

@Override
public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
    // This stops animation on rotation as we have a retained instance.
    boolean shouldNotAnimate = enter && viewsHaveBeenDestroyed;
    viewsHaveBeenDestroyed = false;
    return shouldNotAnimate ? AnimationUtils.loadAnimation(getActivity(), R.anim.none)
            : super.onCreateAnimation(transit, enter, nextAnim);
}

@Override
public void onDestroyView() {
    super.onDestroyView();
    viewsHaveBeenDestroyed = true;
}

Where R.anim.none is just an animation that does nothing. Good luck.