In example navigation action defined in navigation graph:
<action android:id="@+id/action_fragment1_to_fragment2" app:destination="@id/fragment2" app:enterAnim="@anim/right_slide_in" app:popExitAnim="@anim/left_slide_out"/>
When Fragment2
opens and starts sliding into view from the right, Fragment1
disappears instantly (sadly). When Fragment2
is closed and starts sliding to the right, Fragment1
is nicely visible under it, giving a nice stack pop effect (comparable to iOS).
How can I keep Fragment1
visible while Fragment2
slides into view?
At a high level, here's how to make a fragment transition with shared elements: Assign a unique transition name to each shared element view. Add shared element views and transition names to the FragmentTransaction . Set a shared element transition animation.
To animate the transition between fragments, or to animate the process of showing or hiding a fragment you use the Fragment Manager to create a Fragment Transaction . Within each Fragment Transaction you can specify in and out animations that will be used for show and hide respectively (or both when replace is used).
EDIT: This is not the most elegant solution, it is actually a trick but it seems to be the best way to solve this situation until the NavigationComponent
will include a better approach.
So, we can increase translationZ
(starting with API 21) in Fragement2
's onViewCreated
method to make it appear above Fragment1
.
Example:
@Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ViewCompat.setTranslationZ(getView(), 100f); }
As very nice @xinaiz suggested, instead of 100f
or any other random value, we can use getBackstackSize()
to assign to the fragment a higher elevation than the previous one.
The solution was proposed by @JFrite at this thread
FragmentTransaction animation to slide in over top
More details can be found there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With