Bas*_*ssi 1 android fragment android-activity
是否可以在另一个片段中添加片段?
事实上,我有一个包含片段 F1的Activity A,我想在片段 F1 中添加另一个片段 F1.1。
我怎样才能做到这一点。
我希望你明白我的问题
假设你有一个这样的活动布局文件:
<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>
Run Code Online (Sandbox Code Playgroud)
这将MyFragment在活动中创建一个类型的片段,您也可以以编程方式进行:
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
MyFragment fragment = new MyFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
Run Code Online (Sandbox Code Playgroud)
R.id.fragment_container 是将您的片段保存在活动布局文件中的视图的 id,我通常使用框架布局。
最后,对于嵌套片段,您只能以编程方式进行。该方法非常类似于以编程方式将片段添加到活动中,在父片段中您执行以下操作:
Fragment nestedFragment = new MyFragment2();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.add(R.id.nested_frag, videoFragment).commit();
Run Code Online (Sandbox Code Playgroud)
再次R.id.nested_frag是父片段布局文件中容器的 id。
| 归档时间: |
|
| 查看次数: |
5807 次 |
| 最近记录: |