【发布时间】:2023-03-05 11:53:02
【问题描述】:
我现在正在尝试使用导航控制器。我想从LoginFragment 移动到HomeFragment。在LoginFragment 中,我使用下面的代码移动到HomeFragment。
Navigation.findNavController(view).navigate(homeDestination)
但是,当我点击HomeFragment 中的返回按钮时,它会回到LoginFragment,我希望当我点击该按钮时它会关闭应用程序。
以旧的方式,如果我使用活动而不是使用Fragment,我通常会做这样的事情来获得预期的行为:
val intent = Intent(this,HomeActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK.or(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
通过使用这些标志,我可以得到预期的行为。但我不知道如何使用导航控制器实现相同的行为。
【问题讨论】:
-
当您尝试从以前创建新片段时,请使用替换代替添加。 getSupportFragmentManager().beginTransaction() .replace(R.id.container_between, policies, Policies.TAG) .addToBackStack(Policies.TAG).commit();
-
@Shane - 使用 Navigation 时不要直接使用 FragmentTransactions。
-
@Shane 我正在使用安卓导航组件,不再使用片段事务developer.android.com/topic/libraries/architecture/navigation/…
-
请注意,根据Principles of Navigation 和conditional navigation documentation,您不应该使用登录片段作为您的起始目的地。
标签: android kotlin android-navigation android-jetpack android-architecture-navigation