当使用导航架构组件和从导航抽屉启动片段时,您使用菜单和导航图,例如下面的菜单用于导航抽屉,称为“drawer_menu”
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group
android:id="@+id/home_group"
android:checkableBehavior="all">
<item
android:id="@id/nav_fetch_fragment"
android:icon="@drawable/ic_fetch"
android:title="@string/Fetch" />
</group>
</menu>
并在各自的导航图下方
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/navigation_graph"
app:startDestination="@id/nav_splash_fragment">
<fragment
android:id="@+id/nav_splash_fragment"
android:name="manu.apps.movieapp.fragments.SplashFragment"
android:label="Splash"
tools:layout="@layout/splash_fragment">
</fragment>
<fragment
android:id="@+id/nav_home_fragment"
android:name="manu.apps.movieapp.fragments.HomeFragment"
android:label="Home"
tools:layout="@layout/home_fragment">
<action
android:id="@+id/action_home_to_fetch_fragment"
app:destination="@id/nav_fetch_fragment"
app:enterAnim="@anim/anim_slide_in_right"
app:exitAnim="@anim/anim_slide_out_left"
app:popEnterAnim="@anim/anim_slide_in_left"
app:popExitAnim="@anim/anim_slide_out_right">
<argument
android:name="fetchType"
android:defaultValue="fetchClients"
app:argType="string" />
</action>
</fragment>
<fragment
android:id="@+id/nav_fetch_fragment"
android:name="manu.apps.movieapp.fragments.FetchFragment"
android:label="Fetch"
tools:layout="@layout/fetch_fragment">
<argument
android:name="fetchType"
android:defaultValue="fetchAdmin"
app:argType="string"/>
</fragment>
</navigation>
通过这样做,您只需设置下面的代码,当您单击导航抽屉中的 Fetch 时,它将自动打开片段而无需任何额外代码
DrawerLayout drawerLayout = findViewById(R.id.drawer_layout);
navigationView navigationView = findViewById(R.id.navigation_view);
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
AppBaronfiguration appBarConfiguration = new AppBarConfiguration.Builder(R.id.nav_home_fragment, R.id.nav_fetch_fragment)
.setOpenableLayout(drawerLayout)
.build();
NavigationUI.setupWithNavController(navController, appBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
我遇到的问题是在导航图中的“nav_fetch_fragment”参数中,每次我从导航抽屉启动片段时,它都会传递默认值“fetchAdmin”,但我有 3 种不同类型的提取,我希望它们以不同方式解析每当我点击导航抽屉时。我的 Fetch Types 包括“fetchClient”、“fetchCustomer”、“fetchAdmin”,当从导航抽屉单击时,它们应该加载不同的回收站视图数据。
我怎么能这样做,因为通常你只需从你正在导航的片段声明导航方向到你正在导航到的片段,例如下面从主片段导航到获取片段
HomeFragmentDirections.ActionHomeToFetchFragment actionHomeToFetchFragment =
HomeFragmentDirections.actionHomeToFetchFragment ();
actionHomeToFetchFragment.setFetchType("fetchCustomers);
Navigation.findNavController(view).navigate(actionHomeToFetchFragment);