问题
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, theNavController
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