How to postpone a Fragment's enter transition in Android Lollipop?
Solution 1
There's no direct equivalent in Fragment Transitions because Fragments use FragmentTransaction and we can't really postpone something that is supposed to happen in a transaction.
To get the equivalent, you can add a Fragment and hide it in a transaction, then when the Fragment is ready, remove the old Fragment and show the new Fragment in a transaction.
getFragmentManager().beginTransaction()
.add(R.id.container, fragment2)
.hide(fragment2)
.commit();
Later, when fragment2 is ready:
getFragmentManager().beginTransaction()
.addSharedElement(sharedElement, "name")
.remove(fragment1)
.show(fragment2)
.commit();
Solution 2
You can postpone Fragment's enter transition by doing the following:
-
Allow
FragmentTransaction
to re-order & optimize the transactionrequireActivity().supportFragmentManager .beginTransaction() .replace(R.id.container, fragmentB) .addSharedElement(view, "transitionName") .setReorderingAllowed(true) // Set to true .commit()
-
Tell fragmentB to delay the transition after view creation
class TransitionToFragment : Fragment(R.layout.fragment_b) { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) postponeEnterTransition() // Don't start enter transitions yet! ... // Setup your views (view.parent as? View)?.doOnPreDraw { startPostponedEnterTransition() } // Ok, start transitions } }
view.parent.doOnPreDraw { ... }
is used to ensure the fragment's views are measured and laid out for the transition. See Chris Banes's blog for more details.
![Alex Lockwood](https://i.stack.imgur.com/kRYJT.jpg?s=256&g=1)
Alex Lockwood
Creator of Shape Shifter & Android Design Patterns I'm a recent graduate from Carnegie Mellon University with a strong interest in application frameworks, GUI toolkits, the Go Programming Language, and open-source software. I am currently an Android engineer at Lyft. Most of my time on StackOverflow is spent answering questions under the android, java, and golang tags. Sites Blog: androiddesignpatterns.com Google+: +AlexLockwood GitHub: @alexjlockwood Twitter: @alexjlockwood
Updated on June 13, 2022Comments
-
Alex Lockwood about 2 years
In Android Lollipop, the
Activity#postponeEnterTransition()
andActivity#startPostponedEnterTransition()
methods give the Activity the ability to delay starting the entering and exiting shared element transitions until all data is loaded. These work great forActivity
transitions.Is there a way to achieve the same effect when using
Fragment
transitions?