// Fragment A 中定义共享元素 View sharedElement1 = view.findViewById(R.id.shared_element_1); ViewCompat.setTransitionName(sharedElement1, "sharedElementName");
// Fragment B 中定义共享元素 View sharedElement2 = view.findViewById(R.id.shared_element_2); ViewCompat.setTransitionName(sharedElement2, "sharedElementName");
// Fragment A 中跳转到 Fragment B FragmentB fragmentB = new FragmentB(); fragmentB.setSharedElementEnterTransition(new ChangeBounds()); fragmentB.setEnterTransition(new Fade()); fragmentB.setSharedElementReturnTransition(new ChangeBounds());
getFragmentManager().beginTransaction() .addSharedElement(sharedElement1, "sharedElementName") .replace(R.id.fragment_container, fragmentB) .addToBackStack(null) .commit();
getFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() { @Override public void onBackStackChanged() { if (getFragmentManager().getBackStackEntryCount() == 0) { // shared element transition has ended sharedElement1.setVisibility(View.VISIBLE); } } });
// Fragment B 中获取共享元素 View sharedElement2 = view.findViewById(R.id.shared_element_2); sharedElement2.setTransitionName("sharedElementName");
在以上代码实现后,即可在使用Fragments时有效使用多个共享元素。