38.4 Accessing the Navigation Controller
Navigating from one destination to another will usually take place in response to an event of some kind within an app such as a button click or menu selection. Before a navigation action can be triggered, the code must first obtain a reference to the navigation controller instance. This requires a call to the findNavController() method of the Navigation or NavHostFragment classes. The following code, for example, can be used to access the navigation controller of an activity. Note that for the code to work, the activity must contain a navigation host fragment:
NavController controller =
Navigation.findNavController(activity, R.id.demo_nav_host_fragment);
In this case, the method call is passed a reference to the activity and the id of the NavHostFragment embedded in the activity’s layout.
Alternatively, the navigation controller associated with any view may be identified...