android - 在导航组件中以编程方式管理 Fragment BackStack

标签 android android-fragments android-jetpack android-navigation

我正在开发一个使用单个 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 accordinglyI 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/

相关文章:

java - 如何从导航组件中的子 fragment 访问父 fragment 的 View

android - Fragment 背面刷新 - Android 导航

java - Realm - 在应用程序之间共享数据库

java - 使用 Halarious 和 Teleport.org 改造

java.lang.IllegalStateException : Could not find method btnSubmit(View) in a parent or ancestor Context for android:onClick

java - 将位置数据从 fragment 传递到 Android 中的 Activity

java - 使用 getActivity 设置适配器的 fragment 崩溃

android - 我如何在 okhttp Interceptor 中使用 jectpack 数据存储?它需要一个上下文对象

android - Jetpack Compose – BottomBar 位于底部导航下方

Android Studio gradle 2.1.3 问题