Dewey Reed
Dewey Reed

Reputation: 4956

Android Navigation Component: How to add a destination programmatically?

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).

Upvotes: 12

Views: 7156

Answers (2)

Dewey Reed
Dewey Reed

Reputation: 4956

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.

Upvotes: 11

Quang Nhat
Quang Nhat

Reputation: 155

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

Upvotes: 1

Related Questions