【问题标题】:Replacing a ListFragment shows the previous list on top of the new one替换 ListFragment 会在新列表之上显示上一个列表
【发布时间】:2012-11-04 17:44:06
【问题描述】:

我的一个视图中有一个 ListFragment,我在列表中进行了选择,然后将该片段替换为另一个列表。然后我再次在这个列表中进行另一个选择,用另一个列表替换这个列表,但是第三个列表总是显示在原始列表的顶部,就像它从未被替换过一样,为什么会发生这种情况,替换片段时我不能深入三层吗?

这是视图的布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" 
android:orientation="horizontal">


<fragment
    android:id="@+id/frameOne"
    android:name="com.tyczj.bowling.BowlersListFragment"
    android:layout_width="300dp"
    android:layout_height="match_parent"
    android:background="@drawable/list_background_holo" />

<fragment android:name="com.tyczj.bowling.BowlerEntryFrag"
    android:id="@+id/frameTwo"
    android:layout_height="match_parent"
    android:layout_width="fill_parent"/>


</LinearLayout>

frameOne 是总是被替换的片段

列表中的一个项目被选中,我打电话用一个新的替换列表

ft.replace(R.id.frameOne, infoLf).addToBackStack(null).commit();

然后在该列表中进行了另一个选择,所以我再次替换它

ListFragment mBowlersBall = new BowlersBallList(bowlerID);
ft.replace(R.id.frameOne, mBowlersBall);
ft.addToBackStack(null).commit();

那就是当它像这样一起显示两个列表时

【问题讨论】:

    标签: android android-fragments android-listfragment


    【解决方案1】:

    您没有正确替换片段。 首先FragmentTransaction.replace() 方法的文档非常清楚,它指出提供给它的id 应该是要替换其片段的容器的id 而不是 Fragmentid 像你一样被替换。

    其次,您将静态片段(在 xml 布局中声明)与动态片段(在运行时添加)混合,这是您不应该做的。如果您要替换 Fragment,则需要在代码中而不是在 xml 布局中声明 Fragment(请参阅一位 Android 工程师关于此问题的 this response)。

    因此,代替frameOne Fragment 插入一个带有id 的包装布局(例如FrameLayout)。在onCreate 方法中,您将添加您的初始Fragment(BowlersListFragment),然后,基于Fragment 中的选择,您将通过将id 赋予FragmentTransaction.replace() 方法来替换它包装布局和新的Fragment 实例。

    【讨论】:

    • 在某一时刻,我确实设置了它,其中 xml 有框架,片段会去,但是如果你点击后退按钮,片段会被删除,你会有一个空白屏幕,你会有再次点击后退按钮离开活动。我尝试通过检查后台堆栈中添加的片段数量并在只剩下 2 个片段时在活动上调用完成来解决这个问题,但是如果我在运行应用程序时开始的活动上调用完成,google now 屏幕显示向上而不是主屏幕
    • @tyczj 我希望您没有添加带有addToBackStack() 设置的初始片段,因为在这种情况下,Android 会表现出您提到的行为。因此,在onCreate 中添加初始Fragments 不带 addToBackStack
    猜你喜欢
    • 2017-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-04
    • 1970-01-01
    • 1970-01-01
    • 2013-08-26
    相关资源
    最近更新 更多