Search code examples
androidandroid-jetpackandroid-navigationandroid-jetpack-navigationandroid-navigation-graph

Add enter animation to start destination in android navigation component


I know how to add enter and exit animation in action tag in nav graph. I also know how to dynamically add animation using NavOptions when navigating with navController.

I want to know how can we add enter animation for StartDestination in nav graph. I can do it in tow ways:

  1. Applying the animation to the root view of start destination
  2. Using a temporary start destination fragment that will be replaced with original destination fragment.
  3. Applying animation to container(FrameLayout) of the NavHostFragment and add host fragment dynamically

But I'd like to know is there any official solution for this purpose.

Thanks


Solution

  • There is no official way to animate startDestination fragment and I believe you generally should not animate it. There are a few ways your startDestination fragment comes into view and all of them have their own ways to run animations:

    1. Your NavHost is hosted by an activity and this activity is launched from launcher. Launchers normally override window transitions to make your activity appearing nicely.
    2. Your NavHost is hosted by an activity and this activity is launched by another activity. Use activity transitions to override default ones.
    3. Your NavHost is nested in a fragment. The containing fragment runs its own transition when comes into view.

    As you can see in all cases another transition is involved when startDestination fragment is appearing or disappearing, so fragment transition here would likely collide with existing transition, making it look unpleasant.

    At the same time, if you really want to animate it, there are quite a few ways. In addition to mentioned in the question, I can think about these:

    1. If you are using native fragments, set default fragment transitions in app theme with attributes fragmentOpenEnterAnimation, fragmentOpenExitAnimation and so on. Update: it does not make sense in context of the question and is not gonna work anyway.
    2. Override Fragment.onCreateAnimation or Fragment.onCreateAnimator methods in your fragment and return animation / animator needed.