如何使用 Android Jetpack 的导航组件禁用后退导航并删除 Fragment 上的后退箭头?

efa*_*303 2 android android-fragments android-architecture-navigation

我正在将 Google 推荐的单一活动模式与 Android Jetpack 的导航组件一起使用。

片段 1 是身份验证屏幕。在用户通过身份验证并导航到 Fragment 2 后,我想按下 Android 后退按钮关闭应用程序,并删除应用程序栏中的后退箭头。

我已经找到了一些方法,例如onBackPressedDispatcher从后按添加/删除功能,但没有任何方法可以删除后退箭头。

app:popUpTo="@+id/firstFragment"从 Fragment 1 导航到 Fragment 2 时,我也尝试过,但这也不起作用。

这应该可以用一行代码来指定。还在努力寻找。有小费吗?

Moh*_*laa 16

您需要fragment1back-stack导航到fragment2

片段1

<fragment
android:id="@+id/fragment1"
android:name="packagenameforFragment1"
android:label="fragment1"
tools:layout="@layout/fragment_1" >
<action
    android:id="@+id/action_Fragment1_to_Fragment2"
    app:destination="@id/Fragment2_id"
    app:launchSingleTop="true"
    app:popUpTo="@+id/your_MainGraph_id"
    app:popUpToInclusive="true" />
Run Code Online (Sandbox Code Playgroud)

然后当你从 fragment1 导航到 fragment2 时调用它

findNavController(fragment).navigate(R.id.action_Fragment1_to_Fragment2)
Run Code Online (Sandbox Code Playgroud)

要从 Fragment2 中删除后退按钮,您可以使用它

在活动 onCreate()

val appBarConfiguration = AppBarConfiguration
        .Builder(R.id.your_fragment2_id,R.id.any_other_ids_you_want)
        .build()
Run Code Online (Sandbox Code Playgroud)

然后像这样设置你的工具栏

setupActionBarWithNavController(this, yourNavController, appBarConfiguration)
Run Code Online (Sandbox Code Playgroud)

  • 感谢您的回答 - 它实现了从fragment2 中删除后退箭头以及从fragment2 中关闭应用程序的后退按钮。但是,我发现我还需要将我的fragment1 ID添加到appBarConfiguration中,否则它会在fragment1上显示一个后退箭头。 (3认同)