且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在抽屉布局(带有导航抽屉菜单)中使用Android导航组件(导航图)?

更新时间:2022-05-06 22:05:37

导航"组件在使用用于导航抽屉的导航文档更新UI组件,您可以使用setupWithNavController()方法自动将菜单项连接到通过

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:

如果MenuItem的ID与目的地的ID相匹配,则NavController然后可以导航到该目的地.

If the id of the MenuItem matches the id of the destination, the NavController can then navigate to that destination.

因此,您根本不需要onNavigationItemSelected实现,也不需要执行任何FragmentTransactions.只需确保菜单XML中的android:id="@+id/fragment_y"与导航XML中的android:id="@+id/fragment_y"匹配,然后调用setupWithNavController():

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