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

你离开我真会死。 提交于 2020-07-31 03:47:28

问题


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

        <fragment
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        class="androidx.navigation.fragment.NavHostFragment"
        app:navGraph="@navigation/main_nav_graph"
        app:defaultNavHost="true"/>

I have a Drawer layout with a menu , I can't manage to make the navigation to work when I click on the navigation drawer button (it works from main fragment but not when I click on Drawer buttons), If I use the old way to program the navigation drawer using : getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new_fragment).commit();, my navcontroller is lost!! and I get errors like

destination fragment in unknown by navcontroller , because the controller will see the home fragment as currently displayed even if it is not the case (from debug)

public boolean onNavigationItemSelected(MenuItem item) {

        switch (item.getItemId()){
            case R.id.action_1:
                //doesn't work when it current fragment doesnt match the 
                //action_fromfragmentx_to_fragmenty
                Navigation.findNavController(this,R.id.fragment_container)
                .navigate(R.id.action_fromfragmentx_to_fragmenty);
                break;

            //Other menu options...
        }

Hence my question : How should I override this onNavigationItemSelected in Java to make the navigation component work? any link or relative doc about this subject(in Java) ?.


回答1:


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


来源:https://stackoverflow.com/questions/59997397/how-to-use-the-android-navigation-component-nav-graph-in-a-drawer-layout-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!