如何防止使用导航控制器按“后退"按钮后显示先前的片段? [英] How to prevent previous fragment to show up after pressing back button using navigation controller?

查看:363
本文介绍了如何防止使用导航控制器按“后退"按钮后显示先前的片段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在正在尝试使用导航控制器.我想从LoginFragment移到HomeFragment.在LoginFragment中,我使用下面的代码移至HomeFragment.

I am trying to use the navigation controller right now. I want to move from LoginFragment to HomeFragment. In LoginFragment I use this code below to move to HomeFragment.

Navigation.findNavController(view).navigate(homeDestination)

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

However, when I tap the back button in the HomeFragment, it will go back to LoginFragment, I expect that when I tap the button it will close the app.

以旧的方式,如果我使用活动而不是使用Fragment,我通常会执行以下操作来获得预期的行为:

In old way, if I use activity instead of using Fragment, I usually do something like this to get that expected behaviour:

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

通过使用这些标志,我用来获得预期的行为.但是我不知道如何使用导航控制器来实现相同的行为.

By using those flags, I use to get the expected behavior. But I don't how to implement the same behavior using the navigation controller.

推荐答案

Navigation提供了popUpTopopUpToInclusive属性,以作为navigate()操作的一部分从后堆栈中删除片段.

Navigation offers a popUpTo and popUpToInclusive attributes for removing fragments from the back stack as part of a navigate() operation.

这可以用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.

You can also use the id of a <navigation> element as well.

这篇关于如何防止使用导航控制器按“后退"按钮后显示先前的片段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆