Android上的界面展示都是通过Activity实现的,Activity实在是太常用了,我相信大家都已经非常熟悉了,这里就不再赘述。 但是Activity也有它的局限性,同样的界面在手机上显示可能很好看,在平板上就未必了,因为平板的屏幕非常大,手机的界面放在平板上可能会有过分被拉长、控件间距过大等情况。这个时候更好的体验效果是在Activity中嵌入”小Activity”,然后每个”小Activity”又可以拥有自己的布局。这就是Fragment碎片技术。
一、Fragment简介
Android是在Android 3.0 (API level 11)开始引入Fragment的。可以把Fragment想成Activity中的模块,这个模块有自己的布局,有自己的生命周期,单独处理自己的输入,在Activity运行的时候可以加载或者移除Fragment模块。可以把Fragment设计成可以在多个Activity中复用的模块。当开发的应用程序同时适用于平板电脑和手机时,可以利用Fragment实现灵活的布局,改善用户体验。
二、Fragment生命周期
因为Fragment必须嵌入在Acitivity中使用,所以Fragment的生命周期和它所在的Activity是密切相关的。
如果Activity是暂停状态,其中所有的Fragment都是暂停状态;如果Activity是stopped状态,这个Activity中所有的Fragment都不能被启动;如果Activity被销毁,那么它其中的所有Fragment都会被销毁。但是,当Activity在活动状态,可以独立控制Fragment的状态,比如加上或者移除Fragment。
当这样进行fragment transaction(转换)的时候,可以把fragment放入Activity的back stack中,这样用户就可以进行返回操作。
Activity与Fragment生命周期对比图
三、两个简单实例
- 简单的Fragment练习,Activity与Fragment通信
布局文件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"
android:orientation="vertical"
tools:context=".MainActivity" >
<FrameLayout
android:layout_weight="1"
android:id="@+id/content"
android:layout_width="wrap_content"
android:layout_height="0dp" >
</FrameLayout>
<android.support.v4.app.FragmentTabHost
android:id="@+id/tab"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Java文件
package com.example.fragmenttabhost;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.widget.ArrayAdapter;
import android.widget.Toast;
public class MyFragment extends ListFragment{
String show1[] = {