假设你有一个这样的活动布局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment android:name="com.example.frag.MyFragment"
android:id="@+id/list"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
</LinearLayout>
这将在活动中创建MyFragment 类型的片段,您也可以通过编程方式进行:
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
MyFragment fragment = new MyFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
R.id.fragment_container 是将片段保存在活动布局文件中的视图的 ID,我通常使用框架布局。
最后,对于嵌套片段,您可以only 以编程方式进行。该方法非常类似于以编程方式将片段添加到活动中,在您执行的父片段中:
Fragment nestedFragment = new MyFragment2();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.add(R.id.nested_frag, videoFragment).commit();
R.id.nested_frag 再次是父片段布局文件中容器的 id。