片段内的 FragmentActivity

FragmentActivity inside a fragment

我是 android 的新手,我有一些问题。我创建了一个包含两个片段的简单布局,例如:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<FrameLayout
    android:id="@+id/fragment1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

<FrameLayout
    android:id="@+id/fragment2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true" />

我想按如下方式划分此布局:

layout_height of fragment1 : 1/3 height

layout_height of fragment2 : 2/3 height

如何才能做到?

我使用下面的代码来显示片段 1:

 FragmentTransaction transaction =
            getSupportFragmentManager().beginTransaction();

    transaction.add(R.id.fragment1, firstfragment);

但是我不知道如何在fragment2中显示FragmentActivity?

以某种比例放置两个元素 - 使用 LinearLayout 然后将包含的视图的高度设置为 0dp 并按所需比例添加 layoutWeight 属性(例如您的情况下为 1 和 2) 要实例化片段,只需使用您编写的代码两次。您省略了 transaction.commit(); 部分。您必须对它进行两次校准 - 对您要添加的每个片段进行一次。

关于添加 Fragment 的问题Activity 具有误导性 - 您不能将 Activity 放入 Fragment,只能将 Fragment 插入 Activity。

You can achive this layout like this

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="3"
     >

    <FrameLayout
        android:id="@+id/fragment1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <FrameLayout
        android:id="@+id/fragment2"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="2" />

</LinearLayout>

并且在java中你必须在事务中调用commit

//添加Fragment1

FragmentTransaction交易= getSupportFragmentManager().beginTransaction(); transaction.add(R.id.fragment1, firstfragment).commit();

// 添加 Fragment2

FragmentTransaction transaction1 =
        getSupportFragmentManager().beginTransaction();
transaction1.add(R.id.fragment2, secondfragment).commit;

并且您不能将任何 activity 放入 Fragments 中。但你可以从你的片段

开始另一个activity