activity布局中加载fragment
阅读原文时间:2021年04月20日阅读:1

1.首先  创建fragment的类  

package com.qianfeng.fragmentdemo;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Fragment1 extends Fragment {
    /**
     * 当系统第一次绘制fragment的用户界面时回调的方法
     *  返回当前fragment的根layout的view
     *  第一个参数 布局加载器对象
     *  第二个参数 标示父容器
     *  第三个参数 bundle 传递数据
     */
    /**
     * 当系统第一次绘制fragment的用户界面是回调的方法
     * 返回当前fragment的layout的view
     * 
     * 第一个参数:布局加载器对象
     * 第二个参数:表示父容器
     * 第三个参数: bundle 传递数据的
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        //1参数 标示当前布局的资源ID   2参数 标示当前布局的父布局  3参数 是否需要追加父布局
        View view=inflater.inflate(R.layout.activity_fragment1, container, false);

        return view;
    }
}

2,之后在activity的布局中调用Fragment   一般是 name=包名+类名

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

    <fragment 
        android:name="com.qianfeng.fragmentdemo.Fragment1"
        android:id="@+id/fragment1"
        android:layout_height="match_parent"
        android:layout_width="0dp"
        android:layout_weight="1"
        />
    <fragment 
        android:name="com.qianfeng.fragmentdemo.Fragment2"
        android:id="@+id/fragment2"
        android:layout_height="match_parent"
        android:layout_width="0dp"
        android:layout_weight="1"
        />

    <!-- 
       android:name 指定activity中引入的fragment的 包名.类名
       android:id="" 指定fragment的唯一标示
     -->
</LinearLayout>

这样一个布局加载fragment就完成了