Android 以编程方式添加多个片段
我使用片段事务将两个片段添加到一个活动中。但当应用程序启动时,只会显示第一个片段。代码如下: 主要活动Android 以编程方式添加多个片段,android,android-layout,Android,Android Layout,我使用片段事务将两个片段添加到一个活动中。但当应用程序启动时,只会显示第一个片段。代码如下: 主要活动 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FragOne firstButton = new FragOne(); F
@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>
因此,我不确定问题出在哪里……我看到了许多添加一个片段的示例。我不确定,但有可能两个片段实际上都添加了,但因为它们完全相同,并且位于线性布局中-一个隐藏另一个 如果我是你,我会将主要活动中的布局更改为相对布局,并将片段添加到两个不同的占位符,以检查这是否是问题所在
我实际上还没有运行这个程序,所以它可能是完全其他的东西。。。祝你好运 是的,你是对的,片段都被添加了,但问题是片段布局是一个一个地添加的……问题在于片段代码
View view = inflater.inflate(R.layout.frag_one, container, false);
改为
View view = inflater.inflate(R.layout.frag_one, null);
通过确保LinearLayout的方向设置为垂直而不是默认的水平,我的问题得以解决。因为两个片段xml文件的高度参数都是“匹配父对象”
因此,你的第一个碎片在他父母的整个高度上膨胀
当其他碎片加入时,它们就没有位置了
因此,在onCreateView方法中将容器参数设置为null不是解决问题的正确方法
你只需要设置
android:layout\u height=“wrap\u content”我知道现在回答这个问题已经太迟了,但我已经解决了问题。您的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
已将布局高度设置为match\u parent
。它不会占据整个屏幕吗
只要让它
wrap_content
就可以了。刚刚解决了我和你一样的问题。我也有同样的问题。你解决了吗?这救了我。谢谢这也救了我。谢谢
<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>