您可以将Fragment视为Activity的模块化部分,它有自己的生命周期,接收自己的输入事件,并且可以在Activity正在运行时添加或删除(类似于可以重用在不同的Activity的“子Activity”)。本课程显示如何使用支持库(Support Library)扩展Fragment类,以便您的应用程序仍然与运行低至Android 1.6的系统版本的设备兼容。
在开始本课程之前,您必须将Android项目设置为使用支持库。如果您以前未使用支持库,请按照支持库安装文档将项目设置为使用v4库。但是,您还可以通过使用与Android 2.1(API级别7)兼容的v7 appcompat库且包括应用栏,在Activity同样包括Fragment API。
创建Fragment类
要创建一个Fragment,扩展Fragment类,然后覆盖关键生命周期方法来插入应用程序逻辑,类似于使用Activity类的方式。
创建Fragment时的一个区别是,必须使用onCreateView()
回调来定义布局。事实上,这是你需要为了得到一个Fragment运行唯一的回调。例如,这里有一个简单的Fragment,它指定了自己的布局:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.ViewGroup;
public class ArticleFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.article_view, container, false);
}
}
就像一个Activity,一个Fragment应该实现其他生命周期回调,允许你管理它的状态,因为它被添加或从Activity中删除,并且Activity在它的生命周期状态之间转换。例如,当调用Activity的onPause()
方法时,Activity中的任何Fragment也接收对onPause()
的调用。
使用XML向Activity添加Fragment
虽然Fragment是可重用的,但是模块化的UI组件,Fragment类的每个实例都必须与父FragmentActivity相关联。您可以通过在Activity布局XML文件中定义每个Fragment来实现此关联。
注意:FragmentActivity是支持库中提供的一种特殊Activity,用于处理早于API级别11的系统版本上的Fragment。如果所支持的最低系统版本是API级别11或更高版本,则可以使用常规Activity。
这是一个示例布局文件,当设备屏幕被视为“large”(由目录名称中的large限定符指定)时,将两个Fragment添加到Activity。
res / layout-large / news_articles.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<fragment android:name="com.example.android.fragments.HeadlinesFragment"
android:id="@+id/headlines_fragment"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
<fragment android:name="com.example.android.fragments.ArticleFragment"
android:id="@+id/article_fragment"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="match_parent" />
</LinearLayout>
然后将布局应用到您的Activity:
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
public class MainActivity extends FragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_articles);
}
}
您使用v7 appcompat库,您的Activity应该扩展AppCompatActivity,它是FragmentActivity的子类。
注意:通过在布局XML文件中定义Fragment将Fragment添加到Activity布局时,无法在运行时删除该Fragment。如果计划在用户交互期间交换Fragment,则必须在Activity首次启动时将Fragment添加到Activity,如下一课所示。