Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 584
Dewey Reed Avatar asked Mar 29 '19 10:03

Dewey Reed


2 Answers

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.

like image 80
Dewey Reed Avatar answered Oct 15 '22 10:10

Dewey Reed


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

like image 25
Quang Nhat Avatar answered Oct 15 '22 11:10

Quang Nhat