碎片
碎片可看作另外一种形式的活动,可以创建碎片来包含视图。
碎片总是嵌入在活动中,一般有两种常见形式:
1、碎片A和碎片B分别处于不同的活动中,当选择碎片A中的某一项时,触发碎片B启动;
2、碎片A和碎片B处于同一个活动中,共享同一活动,以创建更佳的用户体验。
点此下载完整源码~(代码适用于本文章所讲)
1、创建一个名为“Fragments”的项目,在res/layout文件夹下,分别新建fragment1.xml、fragment2.xml;在当前包名下,分别新建Fragment1.java、Fragment2.java:
fragment1.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#00FF00"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="This is fragment #1"
android:textColor="#000000"
android:textSize="25sp" />
</LinearLayout>
fragment2.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFFE00"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="This is fragment #2"
android:textColor="#000000"
android:textSize="25sp" />
</LinearLayout>
Fragment1.java:
package net.zenail.fragments;
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基类
// 绘制碎片UI:使用一个LayoutInflauter对象来增大指定XML文件中的UI。container参数引用父ViewGroup,准备用于嵌入碎片的活动。
// savedInstanceState参数允许将碎片还原到前一次保存的状态。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.fragment1, container, false);
}
}
Fragment2.java:
package net.zenail.fragments;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment2 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.fragment2, container, false);
}
}
2、在main.xml文件中添加两个碎片:
<fragment
android:id="@+id/fragment1"
android:name="net.zenail.fragments.Fragment1"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1"
tools:layout="@layout/fragment1" />
<fragment
android:id="@+id/fragment2"
android:name="net.zenail.fragments.Fragment2"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1"
tools:layout="@layout/fragment2" />
3、运行,效果如下: