以编程方式添加多个片段

Arl*_*ant 8 android android-layout

我正在使用Fragment事务向活动添加两个片段.但是,当应用程序启动时,只会显示第一个片段.这是代码:

主要活动

    @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();
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

所以我不确定会出现什么问题......我看到很多例子都添加了一个片段.

Dro*_*man 3

我不确定,但有可能两个片段实际上都已添加,但因为它们完全相同并且位于 LinearLayout 中 - 一个片段隐藏了另一个片段。

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

我实际上还没有运行该程序,因此它可能完全是其他东西......祝你好运!