Fragment 没有被替换而是放在前一个之上 [英] Fragment is not being replaced but put on top of the previous one

查看:16
本文介绍了Fragment 没有被替换而是放在前一个之上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

活动:

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();

视图中的代码:

<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:

  1. 您不能替换静态放置在 xml 布局文件中的片段.您应该在布局中创建一个容器(例如 FrameLayout),然后使用 FragmentTransaction 以编程方式添加片段.

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

FragmentTransaction.replace 期望包含片段的容器的 id 而不是片段的 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.

这篇关于Fragment 没有被替换而是放在前一个之上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆