目录
1. Fragment是什么
- fragment表示 Activity 中的行为或用户界面部分。可以将多个片段组合在一个 Activity 中来构建多窗格 UI
- fragment是activity的模块化组成部分
- fragemnt性质:
- 有自己的生命周期
- 可以接收输入事件,并且可以在activity运行时添加或者删除片段
- fragment必须依附在activity中(Activity暂停,fragment暂停,销毁也销毁)
- activity运行时,可以独立操作每个片段,也可以在fragment和activity之间进行通信
- 有自己的生命周期
1.1. 设计原理和实例
- 新闻应用可以使用一个片段在左侧显示文章列表,使用另一个片段在右侧显示文章 — 两个片段并排显示在一个 Activity 中,每个片段都具有自己的一套生命周期回调方法,并各自处理自己的用户输入事件。 因此,用户不需要使用一个 Activity 来选择文章,然后使用另一个 Activity 来阅读文章,而是可以在同一个 Activity 内选择文章并进行阅读
2. 创建fragment
通过创建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布局中
<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中调用该fragment
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);
}
}
2.1. fragment的生命周期
生命周期 | 含义 | 主要内容 |
---|---|---|
onCreate() | 系统会在创建片段时调用此方法 | 初始化组件 |
onCreateView() | 系统会在片段首次绘制其用户界面时调用此方法。 要想为您的片段绘制 UI 您从此方法中返回的 View 必须是片段布局的根视图 |
|
onPause() | 系统将此方法作为用户离开片段的第一个信号(但并不总是意味着此片段会被销毁)进行调用 | 确认在当前用户会话结束后仍然有效的任何更改 |
2.2 添加用户界面:融入到Activity中
- 步骤1: 创建一个布局文件
example_fragment.xml
- 步骤2: 在
fragment
类中加载布局
public static class ExampleFragment extends Fragment {
// container:您的片段布局将插入到的父 ViewGroup
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.example_fragment, container, false);
}
}
- 步骤3: 在
activity
中添加片段- 方法1:直接在布局文件中添加:当系统创建此
Activity
布局时,会实例化在布局中指定的每个片段,并为每个片段调用onCreateView()
方法,以检索每个片段的布局。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android&
- 方法1:直接在布局文件中添加:当系统创建此