第一行代码之Fragment

Fragment(碎片)是Android3.0引入的全新概念,是一种可以嵌入到活动中的UI片段,为了更加合理和充分的利用大屏幕的空间,一般在平板上使用广泛。

Fragment的使用

这里写一个最简单的Fragment测试项目,命名为FragmentTest,在一个活动中添加两个Fragment,并让这两个Fragment平分屏幕空间。

  • 创建一个充当Fragment的布局文件,命名为left_fragment.xml 。
<?xml version="1.0" encoding="utf-8"?>
<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>
  • 在建立一个 right_fragment.xml文件,将布局文件的背景设置为绿色。
<?xml version="1.0" encoding="utf-8"?>
<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:id="@+id/text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:textSize="20sp"
        android:text="This is right fragment"/>

</LinearLayout>
  • 自定义LeftFragment类继承Fragment,重写onCreate()方法,然后通过这个方法中的inflater将刚才建立的left_fragment.xml布局文件加载进来。

    public class LeftFragment extends Fragment {
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.left_fragment, container, false);
            return view;
        }
    }
    
  • 在创建RightFragment类继承Fragment,同样重写onCreate()方法,并加载布局文件

    public class RightFragment extends Fragment {
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.right_fragment, container, false);
            return view;
        }
    }
    
  • 修改activity_main.xml布局文件

    <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"
         >
    
        <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"
            />
    
         <fragment 
            android:id="@+id/right_fragment"
            android:name="com.example.fragmenttest.RifhtFragment"
            android:layout_width="0dp"
            android:layout_height="match_parent"
        android:layout_weight="3"
            />
    
    </LinearLayout>
    

这样简单的Fragment测试项目已经写好,运行项目,在平板中观察。