以编程方式添加多个片段

时间:2013-01-27 15:52:45

标签: android android-layout

我正在使用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>

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

5 个答案:

答案 0 :(得分: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>

观察LinearLayout将layout_height设置为match_parent。它不会占据整个屏幕吗?

只需将其设为wrap_content即可。刚刚解决了我的情况与你的情况相同。

答案 1 :(得分:3)

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

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

我实际上没有运行程序,所以它可能完全是另一回事......祝你好运!

答案 2 :(得分:3)

因为片段xml文件的高度参数是&#34; match_parent&#34;

<?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不是解决问题的正确方法。

你只需要设置 机器人:layout_height =&#34; WRAP_CONTENT&#34;

答案 3 :(得分:1)

我的问题是通过确保LinearLayout将其方向设置为垂直而不是默认水平来解决的。

答案 4 :(得分:0)

是的你是对的,片段都被添加但问题是片段布局被添加到另一个......问题出在片段代码

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

更改为

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