【发布时间】:2012-09-13 19:34:13
【问题描述】:
我在 android fragment backstack 的工作方式上遇到了一个大问题,如果提供任何帮助,我将不胜感激。
假设你有 3 个片段
[1] [2] [3]
我希望用户能够导航[1] > [2] > [3],但在返回的路上(按下返回按钮)[3] > [1]。
正如我想象的那样,这将通过在创建将片段 [2] 带入 XML 中定义的片段持有者的事务时不调用 addToBackStack(..) 来实现。
事实上,如果我不想在用户按下[3] 上的返回按钮时再次出现[2],我就不能在显示片段[3] 的事务中调用addToBackStack。这似乎完全违反直觉(可能来自 iOS 世界)。
无论如何,如果我这样做,当我从[1] > [2] 出发并按回时,我会按预期返回[1]。
如果我去[1] > [2] > [3] 然后按回我跳回[1](如预期的那样)。
现在,当我尝试再次从[1] 跳转到[2] 时,就会发生奇怪的行为。首先,[3] 会在 [2] 出现之前短暂显示。如果此时我按回[3],则会显示,如果我再次按回,应用程序将退出。
谁能帮我理解这里发生了什么?
这是我的主要活动的布局 xml 文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<fragment
android:id="@+id/headerFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
class="com.fragment_test.FragmentControls" >
<!-- Preview: layout=@layout/details -->
</fragment>
<FrameLayout
android:id="@+id/detailFragment"
android:layout_width="match_parent"
android:layout_height="fill_parent"
/>
更新 这是我用来通过 nav heirarchy 构建的代码
Fragment frag;
FragmentTransaction transaction;
//Create The first fragment [1], add it to the view, BUT Dont add the transaction to the backstack
frag = new Fragment1();
transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.detailFragment, frag);
transaction.commit();
//Create the second [2] fragment, add it to the view and add the transaction that replaces the first fragment to the backstack
frag = new Fragment2();
transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.detailFragment, frag);
transaction.addToBackStack(null);
transaction.commit();
//Create third fragment, Dont add this transaction to the backstack, because we dont want to go back to [2]
frag = new Fragment3();
transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.detailFragment, frag);
transaction.commit();
//END OF SETUP CODE-------------------------
//NOW:
//Press back once and then issue the following code:
frag = new Fragment2();
transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.detailFragment, frag);
transaction.addToBackStack(null);
transaction.commit();
//Now press back again and you end up at fragment [3] not [1]
非常感谢
【问题讨论】:
-
但片段重叠,当我从片段 C 回压到片段 A 时。
-
我也有同样的问题,请问如何解决?
-
参考我的答案。它可能对你有帮助 stackoverflow.com/questions/14971780/…>
标签: android android-fragments back-stack