Android的 - 片段.replace()不会取代内容 - 把它放在顶部放在、把它、片段、内容

2023-09-06 13:30:16 作者:≮梦之★情缘≯

活动:

...
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        Fragment1 fragment = new Fragment1();
        Fragment2 fragment2 = new Fragment2();

        transaction.replace(R.id.Fragment1, fragment);
        transaction.addToBackStack(null);
        transaction.commit();


        FragmentTransaction transaction2 = getSupportFragmentManager().beginTransaction();
        transaction2.replace(R.id.Fragment1, fragment2);
        transaction2.addToBackStack(null);
        transaction2.commit();

code的看法:

Code in the view:

<fragment
    android:id="@+id/Fragment1"
    android:name="com.landa.fragment.Fragment1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/include1" /> 

现在的问题是,内容并不真正被替换 - 它被放到了首位(使其重叠)

The problem is, the content doesn't really get replaced - it gets put on top (so it overlaps).

当我点击回来,第一个片段被显示正常(无第二),但最初都是可见的(我想只有最后一个是可见的)。

When I click back, the first fragment gets shown properly (without the second), but initially both are visible (I want only the last one to be visible).

我是什么在这里失踪?

推荐答案

您正在做的两件事情错在这里:

You are doing two things wrong here:

您无法替代的片段,它是静态放置在 XML 布局文件。您应该创建布局容器(如的LinearLayout ),然后编程方式使用 FragmentTransaction 添加片段。

You cannot replace a fragment that is statically placed in an xml layout file. You should create a container (e.g. a LinearLayout) in the layout and then add the fragment programatically using FragmentTransaction.

FragmentTransaction.replace预计包含片段,而不是该片段作为第一个参数的id容器的标识。所以,你应该传递的第一个参数为你添加的第一个分片到容器的id。

FragmentTransaction.replace expects the id of the container that contains the fragment and not the id of the fragment as the first parameter. So you should pass the first argument as the id of the container that you added the first fragment to.

您可以参考此链接了解更多详情。

You can refer to this link for more details.