1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| 1.创建 NavGraph(导航图):在 res/navigation 目录下创建 nav_graph.xml <?xml version="1.0" encoding="utf-8"?> <navigation xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" app:startDestination="@id/homeFragment">
<fragment android:id="@+id/homeFragment" android:name="com.example.ui.HomeFragment" android:label="Home" > <action android:id="@+id/action_homeFragment_to_detailFragment" app:destination="@id/detailFragment" /> </fragment>
<fragment android:id="@+id/detailFragment" android:name="com.example.ui.DetailFragment" android:label="Detail" /> </navigation>
2.在 Activity 中绑定 NavHostFragment <androidx.fragment.app.FragmentContainerView android:id="@+id/nav_host_fragment" android:name="androidx.navigation.fragment.NavHostFragment" android:layout_width="match_parent" android:layout_height="match_parent" app:navGraph="@navigation/nav_graph" />
3.跳转 Fragment NavController navController = Navigation.findNavController(view); navController.navigate(R.id.action_homeFragment_to_detailFragment); 或者 使用 Safe Args 传参 HomeFragmentDirections.ActionHomeFragmentToDetailFragment action = HomeFragmentDirections.actionHomeFragmentToDetailFragment(); navController.navigate(action);
|