动态添加Fragment

1. 在父视图中设置 Fragment 挂载点

  (1): 静态挂载

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

    <fragment
        android:id="@+id/left_fragment"
        android:name="com.example.fragmenttest.LeftFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"/>

</LinearLayout>

  

  (2): 动态挂载

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="horizontal">
    
    <FrameLayout
        android:id="@+id/right_fragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"/>

</LinearLayout>


 

2. 创建 Fragment 实例

  (1): 新建java类,继承 android.support.v4.app.Fragment (使用支持库,可以让fragment在所有Android系统版本中保持功能一致性)

public class DemoFragment extends Fragment

  

  (2): 重写 Fragment 中的 onCreateView 方法, 加载Fragment布局文件 

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    /*
    *参数1:布局资源id
    * 参数2:挂载该视图的父视图对象
    * 参数3:是否将视图挂载到父视图中,因为我们使用 FragmentManger 动态添加,所以此处为 false
    * */
    View view = inflater.inflate(R.layout.fragment_left, container, false);
    return view;
}

3.  获取 FragmentManager 对象

//在Activity和Fragment中,通过 getSupportFragmentManager() 方法可以获取 FragmentManager 对象
FragmentManager fm = getSupportFragmentManager();

4.开启一个 FragmentManager 对象的事务

//通过 FragmentManager 对象的 beginTransaction() 方法,开启事务
FragmentTransaction transaction = fm.beginTransaction();

5. 向容器中添加或替换 Fragment 实例

/*
* 通过 Transaction 对象的 add()或replace()方法,添加或替换 Fragment 对象。
* 参数1:挂在Fragment对象的容器id
* 参数2:被添加或替换的Fragment对象
* */
transaction.replace(R.id.right_fragment, fragment);

6. 提交事务

//提交事务
transaction.commit();


 

原文地址:https://www.cnblogs.com/yingtoumao/p/8615952.html