10

I have a fragment, which shows enter animation, I set transition by

this.setEnterTransition(transition);

After that I want to show another animation. But I need to know when transition animation ends to start the second one.

For activity there is a callback like onEnterAnimationComplete() but it is not called when Fragment's transition ends.

Is there any way to know when enter transition ends for the Fragment?

Alex Wih
  • 1,015
  • 2
  • 11
  • 24

2 Answers2

5
transition.addListener(new Transition.TransitionListener() {
                    @Override
                    public void onTransitionStart(Transition transition) {}

                    @Override
                    public void onTransitionEnd(Transition transition) {}

                    @Override
                    public void onTransitionCancel(Transition transition) {}

                    @Override
                    public void onTransitionPause(Transition transition) {}

                    @Override
                    public void onTransitionResume(Transition transition) {}
                });

                this.setEnterTransition(transition);
4

If you have the following setup:

FragmentA calls FragmentB with a SharedElementEnterTransition like

private final TransitionSet transition = new TransitionSet()
        .addTransition(new ChangeBounds());
//...
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction()
            .replace(R.id.container, fragment, fragment.getClass().getSimpleName());

transaction.addSharedElement(view, view.getTransitionName());
fragment.setSharedElementEnterTransition(transition);
fragment.setSharedElementReturnTransition(transition);
transaction.commit();

to listen for the end of the SharedElementTransition in your second Fragment. Then you have to get the SharedElementEnterTransition in your FragmentB's onAttach like:

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    TransitionSet transitionSet = (TransitionSet) getSharedElementEnterTransition();
    if (transitionSet != null) {
        transitionSet.addListener(new Transition.TransitionListener() {
            @Override
            public void onTransitionEnd(@NonNull Transition transition) {
                // remove listener as otherwise there are side-effects
                transition.removeListener(this);
                // do something here
            }

            @Override
            public void onTransitionStart(@NonNull Transition transition) {}
            @Override
            public void onTransitionCancel(@NonNull Transition transition) {}
            @Override
            public void onTransitionPause(@NonNull Transition transition) {}
            @Override
            public void onTransitionResume(@NonNull Transition transition) {}
        });
    }
}

As pointed out in the comments of this answer there is a bug when not setting the listener in onAttach().

luckyhandler
  • 10,651
  • 3
  • 47
  • 64