替换片段(Fragment replace())未替换所有片段

4
如果我用相同的viewId为片段A和B调用add(),然后尝试使用片段C在该viewId上调用replace(),那么只有片段A被删除,最终剩下了片段B和C。根据文档,应该同时用C替换A和B...或者我读错了文档?以下是一种执行此操作的组合:
public class FragmentActivity extends SherlockFragmentActivity {
    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        getSupportFragmentManager().beginTransaction().add(R.id.fragment, new FragmentA()).add(R.id.fragment, new FragmentB()).commit();

        ((Button) findViewById(R.id.swap)).setOnClickListener(new View.OnClickListener() {          
            @Override
            public void onClick(final View view) {
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment, new FragmentC()).commit();
            }
        });
    }
}

谢谢,我刚刚添加了一小段代码。 - Sekhar Ravinutala
1个回答

0
从文档上看,.replace 调用了一个以片段作为参数的方法。所以我猜它只是用来替换一个片段的。我真的不明白为什么你会在同一个 id 中添加两个片段。

我按照replace()的说明进行操作:这实际上相当于为所有当前使用相同containerViewId添加的片段调用remove(Fragment),然后使用此处给出的相同参数调用add(int, Fragment, String)。 - Sekhar Ravinutala
非常抱歉,我错过了那个部分并且错误地解释了类的定义。这是因为我匆忙浏览导致的。 - Barak

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