我正在开发一个使用单个 Activity 多个 fragment 的项目。我正在使用Jetpack Navigation Components
。我可以使用 NavGraph, NavHost and NavController
进行导航但问题是,there are multiple situations where I need to move from one fragment to other fragment and vice-versa and require to clear the backstack accordingly
。 I was managing these using actions in NavGraph
示例 - 例如,在身份验证成功后从登录 fragment 移至仪表板 fragment ,其中 SigIn fragment 已从后台堆栈中删除。另一个示例 - 如果遇到密码问题,则从 SignIn Fragment 移至 ForgotPassword Fragment,再次从后台清除现有 fragment 以及更多此类情况。 All the mentioned examples required to generate multiple actions from one fragment to other and vice-versa
。使用 individual actions
进行管理在NavGraph
使得Navgraph and Fragments look messed up with multiple actions
。它想以编程方式在 class files
中执行此操作。 如何实现?
注意- I know that Navigation components uses the existing FragmentManager and FragmentTransactions
。我要求来自 Navigation Components
的任何类或 api这样backstack
无需使用FragmentManager and FragmentTransaction
即可轻松管理.
注意:- 我知道我可以通过使用 view.findNavController().navigate(R.id.Nextfragment)
以编程方式从类文件中的一个 fragment 导航到另一个 fragment ,而无需使用 NavGraph但这无助于管理 backstack
最佳答案
好的,这就是它的工作原理..
在 NavController 类
中,已经有一个可用于两种重载表单
的方法,称为 popBackStack(),该方法从后台堆栈中弹出当前 Fragment(如果可用)
和 popBackStack(@IdRes int destinationId, boolean Include) 接受用户指定的目的地(next_fragment_id) 和一个用作 popToInclusive 标志的 bool 值
我做了什么-
binding.tvMoveToSignUp.setOnClickListener {
it.findNavController().apply {
popBackStack(R.id.signInFragment, true)
navigate(R.id.signUpFragment)
}
}
在我上面的例子中, 我首先通过调用 view.findNavController() 获取 NavController,然后通过调用 popBackStack(R. id.signInFragment, true) ,即
SignInFragment 并将 flag popToInclusive 设置为 true 以弹出 SignInFragment
并然后导航到
SignUpFragment通过调用navigate(R.id.signUpFragment)
关于android - 在导航组件中以编程方式管理 Fragment BackStack,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63361390/