I have a navigation graph that uses this fragment as a home in the main activity XML.
The Navigation component offers a helper class in NavigationUI in the navigation-ui artifact. As per the Update UI components with Navigation documentation for navigation drawers, you can use the setupWithNavController() method to automatically hook up menu items to navigation destinations you set up in your navigation graph by tying the destination item to a menu item:
If the id of the
MenuItemmatches the id of the destination, theNavControllercan then navigate to that destination.
Therefore you don't need a onNavigationItemSelected implementation at all, nor do you need to do any FragmentTransactions. Just make sure that the android:id="@+id/fragment_y" in your menu XML matches the android:id="@+id/fragment_y" in your navigation XML and call setupWithNavController():
NavigationView navView = findViewById(R.id.nav_view);
// This is what sets up its own onNavigationItemSelected
NavigationUI.setupWithNavController(navView, navController);