10

I want to inject a new destination to the current nav graph.

I notice NavGraph has a method void addDestination(@NonNull NavDestination node) but I can't find a proper way to create a NavDestination and navigate to it using navController.navigate(R.id.new_dest_id).

Dewey Reed
  • 4,353
  • 2
  • 27
  • 41

2 Answers2

9

I've got two working ways:

navController.graph.addDestination(ActivityNavigator(this).createDestination().apply {
    id = R.id.new_dest
    setComponentName(ComponentName(context, NewActivity::class.java))
    // or setIntent
})

or this

navController.graph.addDestination(
    navController.navigatorProvider.getNavigator(ActivityNavigator::class.java)
        .createDestination().apply {
            id = R.id.new_dest
            setComponentName(ComponentName(context, NewActivity::class.java))
        }
)

There is also a DSL builder ActivityNavigatorDestinationBuilder.

Fragment is similar. Change ActivityNavigator to FragmentNavigator and use different setters.

I also made a mistake when I added a destination in one graph and tried to navigate to the new destination in another graph. of course that never work.

Dewey Reed
  • 4,353
  • 2
  • 27
  • 41
  • I'm having a similar problem. I want to navigate to a new graph which already has its fragments configured. I was able to create a new destination with NavGraphNavigator, but this creates a completely new graph how do I inflate the one I already have? – Viktor Petrovski May 24 '19 at 09:29
  • @VictorPetrovski You'd better ask a new question about it. BTW, `NavInflater` seems promising. – Dewey Reed May 25 '19 at 03:22
  • Thanks, I already managed to do it. Your code for adding destination gave me a pretty clear picture on how to accomplish what I've wanted!! – Viktor Petrovski May 25 '19 at 08:44
  • do we have java equivalent of this code? – Vasil Valchev May 22 '22 at 18:39
1

Did you try to pass the ID of your newly created Destination in navigate(), like navigate(myDes.getId())

Quang Nhat
  • 135
  • 1
  • 8