无法将多个片段添加到LinearLayout [英] Cannot add multiple fragments to LinearLayout

查看:79
本文介绍了无法将多个片段添加到LinearLayout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用具有垂直方向的LinearLayout列出片段.我以编程方式向容器中添加片段:

I am using a LinearLayout with a vertical orientation to list fragments. I add fragments to the container programmatically like this:

FragmentTransaction ft = fragmentManager.beginTransaction();

Fragment fragment1 = new Fragment();
ft.add(R.id.llContainer, fragment1);

Fragment fragment2 = new Fragment();
ft.add(R.id.llContainer, fragment2);

ft.commit();

但是它仅显示第一个片段.为什么?

But it only shows the first fragment. Why?

推荐答案

LinearLayout中可以有多个片段.

You can have multiple fragments in a LinearLayout.

根据文档

如果要将多个片段添加到同一容器中,则添加片段的顺序将决定它们在视图层次结构中的显示顺序

If you're adding multiple fragments to the same container, then the order in which you add them determines the order they appear in the view hierarchy

您的代码的问题在于,因为您未指定片段标签,所以默认使用容器ID.由于两个事务的容器ID相同,因此第二个事务替换了第一个片段,而不是将其单独添加到容器中.

The problem with your code is that because you didn't specify fragment tags, it defaulted to the container id. Since the container id is the same for both transactions, the 2nd transaction replaced the 1st fragment, rather than added it to the container separately.

要做你想做的事,使用类似的东西:

To do what you want, use something like:

FragmentTransaction ft = fragmentManager.beginTransaction();

Fragment fragment1 = new Fragment();
ft.add(R.id.llContainer, fragment1, "fragment_one");

Fragment fragment2 = new Fragment();
ft.add(R.id.llContainer, fragment2, "fragment_two");

ft.commit();

这篇关于无法将多个片段添加到LinearLayout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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