The key is to use a custom transaction with
transaction.addSharedElement(sharedElement, "sharedImage");
Transition between two fragments between two fragments
In this example, one of two different ImageViews should be translated from ChooserFragment to DetailFragment .
In the ChooserFragment layout ChooserFragment we need the unique transitionName attributes:
<ImageView android:id="@+id/image_first" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_first" android:transitionName="fistImage" /> <ImageView android:id="@+id/image_second" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_second" android:transitionName="secondImage" />
In the ChooserFragments class ChooserFragments we need to pass the View that was clicked and the identifier of the parent Activity that handles the replacement of the fragments (we need an identifier to find out which image resource to show in DetailFragment ). How to convey in detail the information of parental activity, of course, is discussed in other documentation.
view.findViewById(R.id.image_first).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mCallback != null) { mCallback.showDetailFragment(view, 1); } } }); view.findViewById(R.id.image_second).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mCallback != null) { mCallback.showDetailFragment(view, 2); } } });
In the DetailFragment for an ImageView element for a shared element, a unique transitionName attribute is also needed.
<ImageView android:id="@+id/image_shared" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:transitionName="sharedImage" />
In the onCreateView() DetailFragment we must decide which image resource should be shown (if we do not, the common element will disappear after the transition).
public static DetailFragment newInstance(Bundle args) { DetailFragment fragment = new DetailFragment(); fragment.setArguments(args); return fragment; } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View view = inflater.inflate(R.layout.fragment_detail, container, false); ImageView sharedImage = (ImageView) view.findViewById(R.id.image_shared);
Parent Activity receives callbacks and handles fragment replacement.
@Override public void showDetailFragment(View sharedElement, int type) {
Do not forget - Transition itself. This example moves and scales a common item.
@TargetApi(Build.VERSION_CODES.LOLLIPOP) public class DetailsTransition extends TransitionSet { public DetailsTransition() { setOrdering(ORDERING_TOGETHER); addTransition(new ChangeBounds()). addTransition(new ChangeTransform()). addTransition(new ChangeImageTransform()); } }