Shared element transition : activity into fragment nested in another activity Shared element transition : activity into fragment nested in another activity android android

Shared element transition : activity into fragment nested in another activity


The way that transitions work require the new Activity to be created, measured and laid out before any animations can happen. That's so that it can find the view that you want to animate and create the appropriate animation.

In your case this isn't happening because, as stated in the docs, all FragmentTransaction.commit() does is schedule work to be done. It doesn't happen immediately. Therefore when the framework creates your Activity it cant find the view that you want to animate. That's why you don't see an entry animation but you do see an exit animation. The View is there when you leave the activity.

The solution is simple enough. First of all you can try FragmentManager.executePendingTransactions(). That still might not be enough. The transitions framework has another solution:

In the onCreate of Activity postponeEnterTransition(). This tells the framework to wait until you tell it that its safe to create the animation. That does mean that you need to tell it that its safe (via calling startPostponedEnterTransition()) at some point. In your case that would probably be in the Fragments onCreateView.

Here's an example of how that might look like:

Activity B

@Overrideprotected void onCreate(Bundle savedInstanceState) {    // etc    postponeEnterTransition();}

Fragment B

@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {    View sharedView = root.findViewById(R.id.shared_view);    sharedview.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {        @Override        public boolean onPreDraw() {            sharedview.getViewTreeObserver().removeOnPreDrawListener(this);            getActivity().startPostponedEnterTransition();            return true;        }    });}

Thanks to Alex Lockwood for his detailed blog posts about the Transitions framework.