以编程方式添加多个片段

8
我将使用Fragment事务将两个片段添加到活动中。但是当应用程序启动时,只有第一个片段被显示出来。以下是代码:

MainActivity


我正在使用片段事务将两个片段添加到活动中。但是应用程序启动时,只有第一个片段被显示出来。以下是代码:
    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    FragOne firstButton = new FragOne();
    FragmentTwo secButton = new FragmentTwo();

    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

    transaction.add(R.id.frag_container, firstButton);
    transaction.add(R.id.frag_container, secButton);

    transaction.commit();
}

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:id="@+id/frag_container"
    android:layout_height="fill_parent" 
    android:orientation="horizontal">

</LinearLayout>

frag_one.xml和frag_two.xml非常相似

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
   <Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button One" />
</LinearLayout>

所以我不确定问题出在哪里...我看到很多例子都是添加一个片段。


我遇到了同样的问题。你解决了吗? - Zip
5个回答

4

我知道回答已经太晚了,但我解决了问题。你的frag_one.xml和frag_two.xml看起来像:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
   <Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button One" />
</LinearLayout>

请注意LinearLayoutlayout_height设置为match_parent。这样它不会占据整个屏幕吗?

只需将其设置为wrap_content即可解决问题。我刚刚解决了和你完全相同的问题。


1
这个帮了我大忙了。谢谢! - marienke
这也帮了我大忙。谢谢! - Jignesh

3
由于两个片段 XML 文件的高度参数均为“match_parent”,因此产生了这种情况。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    *android:layout_height="match_parent"  WRONG!!! need to be "wrap_content"*
    android:orientation="vertical" >
   <Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button One" />
</LinearLayout>

因此,您的第一个片段会在其父级上整体充气,当添加其他片段时,它们没有位置。
因此,在onCreateView方法中将容器参数设置为null不是解决问题的正确方法。
您只需要设置android:layout_height="wrap_content"。

3

我不确定,但有可能这两个片段都被添加了,只是因为它们完全相同并位于LinearLayout中,一个隐藏了另一个。

如果我是你,我会在主活动中更改布局为相对布局,并将片段添加到两个不同的占位符中以检查是否存在此问题。

我实际上还没有运行程序,所以可能是其他问题...祝好运!


1

我的问题得到解决是因为确保LinearLayout的方向设置为垂直,而不是默认的水平。


0

是的,你说得对,这些片段都被添加了,但问题在于片段布局重叠了...问题出在片段代码中。

View view = inflater.inflate(R.layout.frag_one, container, false);

改为

View view = inflater.inflate(R.layout.frag_one, null);

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