How to use the Android Navigation component (Nav Graph) in a Drawer Layout (with navigation drawer Menu)?

后端 未结 1 1018
情深已故
情深已故 2021-01-24 00:41

I have a navigation graph that uses this fragment as a home in the main activity XML.

        

        
1条回答
  •  无人及你
    2021-01-24 01:25

    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 MenuItem matches the id of the destination, the NavController can 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);
    

    0 讨论(0)
提交回复
热议问题