参考 : http://developer.android.com/guide/components/fragments.html
一 概述
Android 3.0(API level 11)加入,为了使界面更灵活,可复用,动态生成。
二 要点:
- 必须嵌入在Activity中,生命周期受Activity影响
- 当在Activity中添加Fragment时,实际是在加入到ViewGroup中。(可直接用)
- 成为Activity的一部分,不一定要Layout,可以做一些不需要看见的工作。
三 使用方法
1. 必须实现的方法
- onCreate() : 必要的初始化
- onCreateView() :创建视图
- onPause() : 保存数据
2. 基本的fragment类型
- DialogFragment
- ListFragment
- PreferenceFragment
3. 添加Fragment到Activity
3.1 带界面
- 在Activity的layout中声明:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment android:name="com.example.news.ArticleListFragment"
android:id="@+id/list"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
<fragment android:name="com.example.news.ArticleReaderFragment"
android:id="@+id/viewer"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="match_parent" />
</LinearLayout>
- 在代码中动态添加:
注意:需要在Activity的布局中有一块空间给fragment
FragmentManager fragmentManager = getFragmentManager()
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
3.2 不带界面
修改如下方法即可:
add(Fragment, String)
设置Tag 来给其提供唯一标识(比id好)
使用方法:findFragmentByTag()
4. 管理Fragments
通过FragmentManager,FragmentTransaction
- add()
- remove()
- replace()
commit()之前,可以setTransition(),使Fragment 变化带有动画效果。
5. 替换Fragment的事项。
- 貌似只是能替换有界面的,并且没有销毁它。
- 不带界面的fragment即使替换也会一直工作,直到done。
四 与Activity交互
常用方法
- getActivity();
- ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);或者用findFragmentByTag()
创建回调函数
public static class FragmentA extends ListFragment {
...
// Container Activity must implement this interface
public interface OnArticleSelectedListener {
public void onArticleSelected(Uri articleUri);
}
...
}
public static class FragmentA extends ListFragment {
OnArticleSelectedListener mListener;
...
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnArticleSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnArticleSelectedListener");
}
}
...
}
以上是结合官网,归纳的。