返回到后面堆叠的片段

我有我用add()方法添加的片段A,B,C。

当我到达片段C时,有时候我想回到片段A并删除B和C.

我的方法是:

 val backStateName = FragmentA::class.java.name activity.fragmentManager.popBackStackImmediate(backStateName, FragmentManager.POP_BACK_STACK_INCLUSIVE) 

我也有一个specialTag添加到我的片段A,所以我做了一个检查,以确保在我尝试我的方法之前,片段A仍然在后面堆栈。

 val fragmentToGoTo = activity.fragmentManager.findFragmentByTag(specialTag) 

它不会返回null – 这意味着片段仍然可用于后退堆栈。 popBackStackImmediate返回false。 为什么?

当您附加一个片段(或执行任何其他操作时添加/删除/分离等),您可以选择将其添加到堆栈的名称字符串:

 FragmentA fragmentA = (FragmentA) fragmentManager.findFragmentByTag("A"); FragmentTransaction transaction = fragmentManager.beginTransaction(); if (fragmentA != null) { transaction.attach(fragmentA); transaction.addToBackStack("attachA"); transaction.commit(); } 

注意我们传递给addToBackStack()方法的“attachA”字符串。 我们稍后会用它来回头。 假设我们已经执行了其他事务 – 添加/删除/附加/分离了一些其他片段。 现在回到我们称之为popBackStack()方法的状态:

 fragmentManager.popBackStack("attachA", FragmentManager.POP_BACK_STACK_INCLUSIVE); 

如果有一个事务添加到名为“attachA”的后端堆栈,该方法将使我们回到那个状态。

关于你有关返回案例的问题 – 你可能已经阅读了关于这些方法的文档以及它们返回的值。 因为它,我更喜欢使用popBackStack()

 /** * Pop the last fragment transition from the manager's fragment * back stack. If there is nothing to pop, false is returned. * This function is asynchronous -- it enqueues the * request to pop, but the action will not be performed until the application * returns to its event loop. * * @param name If non-null, this is the name of a previous back state * to look for; if found, all states up to that state will be popped. The * {@link #POP_BACK_STACK_INCLUSIVE} flag can be used to control whether * the named state itself is popped. If null, only the top state is popped. * @param flags Either 0 or {@link #POP_BACK_STACK_INCLUSIVE}. */ public abstract void popBackStack(String name, int flags); /** * Like {@link #popBackStack(String, int)}, but performs the operation immediately * inside of the call. This is like calling {@link #executePendingTransactions()} * afterwards. * @return Returns true if there was something popped, else false. */ public abstract boolean popBackStackImmediate(String name, int flags); 

我有同样的行为。 确保你调用popBackStackImmediate和你用来将它添加到你的backstack相同的线程。

另外验证您使用.add()而不是.replace()

无论如何,从来没有保证在这样做的时候不会清除/销毁这个后台。 我通过使用popBackStack()来解决这个问题,直到你到达你想要的片段。

你可以尝试类似于:

 fun popStack(tag: String) { var isPopped = fragmentManager.popBackStackImmediate(tag, FragmentManager.POP_BACK_STACK_INCLUSIVE) if (!isPopped) { fragmentManager.popBackStack() //maybe a loop until you reached your goal. } }