1

FragmentNavigator#navigate():

public void navigate(@NonNull Destination destination, @Nullable Bundle args,
                        @Nullable NavOptions navOptions) {
    // ......

    ft.replace(mContainerId, frag);

    ft.commit();

}

so on. i want fragment to use add。 repalce lead to reLoad every navigate

jay
  • 11
  • 1
  • Welcome to StackOverflow! I don't quite understand your question. Do you want to know why does the AndroidX Navigation library use `ft.replace()` instead of `ft.add()`? What problem do you have with it? Is your Fragment loading as new every time and that is not what you want? – Tim Kist Sep 20 '18 at 08:15
  • As far as I know, that's the expected behavior and Google has no plans to change it. However, there is a tweak: Using DialogFragment does not replace fragments. Have a look to this [answer](https://stackoverflow.com/a/55256858/6154843) for more info – Cris Jul 10 '20 at 07:33

1 Answers1

1

You can provide a custom Navigator for this.

instead of FragmentNavigator by

NavController.getNavigatorProvider().addNavigator().

your custom Navigator must be annotated

@Navigator.Name("fragment")

For example

@Navigator.Name("fragment")

class HookFragmentNavigator(private val delegate: FragmentNavigator) : Navigator<FragmentNavigator.Destination>() {

override fun navigate(
    destination: FragmentNavigator.Destination,
    args: Bundle?,
    navOptions: NavOptions?,
    navigatorExtras: Extras?
): NavDestination? {
    "hook delegate navigate".println()
    return delegate.navigate(destination, args, navOptions, navigatorExtras)
}

override fun createDestination(): FragmentNavigator.Destination {
    return delegate.createDestination()
}

override fun popBackStack(): Boolean {
    return delegate.popBackStack()
}

}

findNavController(R.id.fragment).apply {
            navigatorProvider.addNavigator(
                HookFragmentNavigator(navigatorProvider.getNavigator(FragmentNavigator::class.java))
            )
        }.navigate(
            it,
            null,
            NavOptions.Builder().setAnimal().build()
        )
龚诗豪
  • 11
  • 3
  • Hi, welcome to StackOverflow. It would be really helpful if you could provide some code snippets as en example. On the other hand, remember that you can add some format to your answers and questions to improve readability – Cris Jul 10 '20 at 07:34