I have a shared element in a fragment that belongs to one Activity.
I want to make a shared element transition in Android Lollipop with an element that is part of a fragment that belongs to another activity.
Is it possible?
How can I achieve that?
It's possible.
First, when you detect in your fragment that transition is about to happen, build a array of Pair<View, String>
which you populate with view and transition name.
For example, if you want to animate from thumbnail image to full width image:
Pair[] pairs = new Pair[1];
pairs[0] = new Pair(thumbnailImage, "THUMBNAIL_IMAGE");
Second, pass that array to fragment's activity so it can initiate the actual transition. (I'm using Otto to pass that event up, you can use usual callbacks if you like).
Then, in your activity, start the second activity. (I created a simple method for doing that)
public static void transitionExpand(Activity activity, Intent intent, Pair<View, String>[] sharedElements) {
ActivityOptionsCompat options =
ActivityOptionsCompat.makeSceneTransitionAnimation(activity, sharedElements);
ActivityCompat.startActivity(activity, intent, options.toBundle());
}
In your second activity, you can add the fragment in the usual way. Then, in second fragment's onViewCreated()
method, you can call:
ViewCompat.setTransitionName(fullWidthImage, "THUMBNAIL_IMAGE");
hope it helps
UPDATE: As of v25.1.1 of the support library, these same methods are in the support Fragments. Links to the docs: Fragment.postponeEnterTransition() and Fragment.startPostponedEnterTransition()
ORIGINAL ANSWER:
It's possible, even with a dynamically added Fragment in the second Activity.
You just need to tell the second Activity not to run its Transition animations until the shared elements have been laid out and measured.
In the onCreate
of the second Activity call postponeEnterTransition()
(or supportPostponeEnterTransition()
if you're using the Support Library). Dynamically add your Fragment to this Activity. At the end of the onCreateView
method in the Fragment that you're dynamically adding, call getActivity().startPostponedEnterTransition()
.
This of course assumes you've done everything else required for a shared element transition, but I believe these methods are what you're searching for with your question.
Credit to @alex-lockwood's blog for showing me the light.