Search code examples
androidkotlinandroid-jetpackshared-element-transitionandroid-jetpack-navigation

Android fragment return transitions using shared elements with jetpack navigation


I've been migrating my application to the Android Jetpack navigation component, and am having difficulties with shared element transitions.

The transitionName attribute is set on both fragments, and I am starting the navigation using the following code (per the animation documentation):

findNavController().navigate(
    MainFragmentDirections.actionViewEvent(event.name),
    FragmentNavigatorExtras(
        backgroundElement to "event_card",
        titleElement to "event_name"
    )
)

Initially, this alone didn't work at all. However, after adding the following code to the destination Fragment, the shared elements were animated on entry:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    sharedElementEnterTransition = TransitionInflater.from(context).inflateTransition(android.R.transition.move)
}

However, there is still no shared element return transition. Is it possible to enable the transition on both enter and return? (I previously had this working when the two fragments were separate activities.)

It may be relevant to know I've overridden onSupportNavigateUp in the Activity as recommended by the documentation when using an action bar. The overridden method is below:

override fun onSupportNavigateUp(): Boolean =
        findNavController(R.id.nav_host).navigateUp(appBarConfiguration)
                || super.onSupportNavigateUp()

Solution

  • In my case, the failure to animate the return transition was because Glide was loading an image in the fragment to which I was returning.

    I added a listener as recommended in this answer and it fixed the problem.

    I'll vote to close this question as a duplicate as while I didn't realise that was the issue at first, the solution is the same.