android - 使用导航 Controller 按下后退按钮后如何防止上一个 fragment 出现?

标签 android kotlin android-navigation android-jetpack android-architecture-navigation

我现在正在尝试使用导航 Controller 。我想从 LoginFragment 移动到 HomeFragment。在 LoginFragment 中,我使用下面的代码移动到 HomeFragment

Navigation.findNavController(view).navigate(homeDestination)

但是,当我点击 HomeFragment 中的后退按钮时,它将返回到 LoginFragment,我希望当我点击该按钮时它会关闭应用程序。

以旧的方式,如果我使用 Activity 而不是使用 Fragment,我通常会做这样的事情来获得预期的行为:

val intent = Intent(this,HomeActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK.or(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)

通过使用这些标志,我获得了预期的行为。但我不知道如何使用导航 Controller 实现相同的行为。

最佳答案

导航提供了一个 popUpTopopUpToInclusive作为 navigate() 的一部分从返回堆栈中删除 fragment 的属性操作。

这可以在 XML 中设置:

<!-- Add to your Navigation XML, then use navigate(R.id.go_home) -->
<action
  android:id="@+id/go_home"
  app:destination="@+id/home_fragment"
  app:popUpTo="@+id/destination_to_pop"
  app:popUpToInclusive="true"/>

或以编程方式设置:

NavOptions navOptions = new NavOptions.Builder()
    .setPopUpTo(R.id.destination_to_pop, true)
    .build();
Navigation.findNavController(view).navigate(homeDestination, navOptions)

您还可以使用 <navigation> 的 ID元素也是如此。

关于android - 使用导航 Controller 按下后退按钮后如何防止上一个 fragment 出现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54919101/

相关文章:

android - 如何在导航 View 中获取子菜单的 ID

java - 进度对话框 : Why?

android - 无法创建早于 Android Kit Kat (4.4) 的 Android 模拟器

android - Kotlin - 具有多个标志语法的 getPendingIntent

android - 使用协程更新 UI 异步调用

android - 具有多个顶级目的地的导航图

android - 使用加载 gif 将项目动态添加到 NavigationView

android - 带有图像的惰性列表。如何取消线程?

android - 如何在jetcompose中制作自定义形状

android - 如何在 Kotlin-MVP 的 Adapter 类的 button.setOnClickListener 中显示 fragment 对话框?