Fragment的简单用法
实现: 在一个Activity中添加两个Fragment,并让这两个Fragment平分Activity页面.
1 新建一个 LeftFragment 类,继承自 Fragment . 并写好布局文件 left_fragment.xml.
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class LeftFragment extends Fragment {
    
    public View onCreateView(LayoutInflater inflater, 
            ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.left_fragment, container, false);
        return view;
    }
}
布局文件 left_fragment.xml.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Button" />
</LinearLayout>  
2 用同样的方法再新建一个 RightFragment . 并写好布局文件 right_fragment.xml .
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class RightFragment extends Fragment {
    
    public View onCreateView(LayoutInflater inflater, 
            ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.right_fragment, container, false);
        return view;
    }
}
布局文件 right_fragment.xml.(绿色背景)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#00ff00"
    android:orientation="vertical" >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="This is right fragment"
        android:textSize="20sp" />
</LinearLayout>  
3 修改activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <fragment
        android:id="@+id/left_fragment"
        android:name="com.yassblog.LeftFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />
    <fragment
        android:id="@+id/right_fragment"
        android:name="com.yassblog.RightFragment"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />
</LinearLayout>   
4 启动项目,就会看到MainActivity被分成两个Fragment了
5 注意事项
- activity_main.xml中的<fragment>标签,需要通过 android:name 属性来显式指明要添加的Fragment类名,注意一定要将类的包名也加上.
- 新建 LeftFragment 类时,导Fragment包时会有两个选择, android.app.Fragment是面向 Android 4.0 以上系统的, 另一个包下的 Fragment 主要是用于兼容低版本的 Android 系统.