【问题标题】:Add Fragment into fragment [duplicate]将片段添加到片段中[重复]
【发布时间】:2018-05-17 18:04:43
【问题描述】:

是否可以在另一个片段中添加片段?

确实,我有一个 Activity A,其中包含一个 fragment F1,我想在 中添加另一个 fragment F1.1 >片段 F1.

我该怎么做。

希望你能理解我的问题

【问题讨论】:

标签: android android-activity fragment


【解决方案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>

这将在活动中创建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。

【讨论】:

    【解决方案2】:

    从片段 F1 中,您可以使用以下方法添加新片段:

        FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); 
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); 
        fragmentTransaction.replace(R.id.container, fragment);
        fragmentTransaction.commit();
    

    【讨论】:

      猜你喜欢
      • 2012-11-18
      • 1970-01-01
      • 2017-04-14
      • 1970-01-01
      • 2016-06-27
      • 1970-01-01
      • 1970-01-01
      • 2014-02-07
      • 1970-01-01
      相关资源
      最近更新 更多