添加一个片段后,先前的片段仍然可见。

7
起初,我使用了replace方法将片段添加到返回堆栈中,但是当我按下后退键时,堆栈中的片段会再次调用onCreateView方法。我还在api演示中发现了这种行为,因此我认为这不是一个错误,但我希望实现与活动相似的效果,即当我按下后退键时,先前的活动不会调用onCreate方法。
后来,我发现fragmentManager.add()可以实现我的想法,但另一个问题出现了,当添加第二个片段时,以前的片段仍然可见。
有人能帮我吗?
FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction2 = manager.beginTransaction();
        transaction2.add(R.id.fl, f2);
        transaction2.addToBackStack("Fragment2");
        transaction2.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        transaction2.commit();
6个回答

1

回到使用 replace,并添加一个检查以查看 bundle 是否为 null。

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    ...
    if (savedInstanceState == null) {
        // do work 
        // If the view is being recreated this code won't run
    }
    ...
}

0
如果你是第一次添加片段,你可以像在你的代码中那样添加片段。
Fragment_Home fragment = new Fragment_Home();
        FragmentTransaction fts = (MainActivity.this).getSupportFragmentManager().beginTransaction();
        fts.add(R.id.frame_container, fragment);
//        fts.addToBackStack(fragment.getClass().getSimpleName());
        fts.commit();

如果你想从当前片段移动到其他片段,那么你应该用新的片段替换当前片段。

Fragment_CreateGroup fragment = new Fragment_CreateGroup();
            fts = (MainActivity.this).getSupportFragmentManager().beginTransaction();
//            fts.addToBackStack(fragment.getClass().getSimpleName());
            fts.replace(R.id.frame_container, fragment);
            fts.commit();

这里fts是在顶部定义的FragmentTransaction对象。


1
如果我们再次添加碎片,那么会发生什么?之前的碎片还保持激活吗?如果在杀死新碎片后,我们可以回到之前的碎片,继续上一个碎片吗? - Shubham Agarwal Bhewanewala

0

要解决这个问题,您只需要在xml中更改根内的背景,并放置该代码以避免从先前的片段点击。

android:background="@drawable/background"
android:focusable="true"
android:clickable="true"

0

检查您是否为片段设置了 ARGB 背景。在这种情况下,请将该背景替换为 RGB。A 表示透明。


0

尝试使用“替换”而不是“添加”

代码的一部分

fragmenttransaction.replace(R.id.realtabcontent, Fragment); fragmenttransaction.commit();


1
如果您使用replace函数,则当前的片段将被新片段替换,因此当您点击“后退”时,您不会回到先前的片段,因为它已经被替换了! - Kishan Solanki

-1

尝试使用

manager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); 

在添加新的FragmentTransaction之前,请参见此处


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接