1.定义
Fragment表现Activity中用户界面的一个行为或者是一部分。可以再Activity运行时添加或者删除。
2.生命周期
onCreate():在创建fragment时系统会调用此方法。可以在初始化想要在fragment中保持的那些必要的组件。
onCreateView():第一次为fragment绘制用户界面时调用此方法。返回函数所绘出的fragment的根View。
onPause():通常要在这里提交任何需要持久化的变化。
3.将fragment添加到activity之中
①.在activity的布局文件里声明fragment
在生命周期方面,activity与fragment之间一个很重要的不同,就是在各自的后台栈中是如何存储的。仅当你在一个事务被移除时,通过显式调用addToBackStack()请求保存的实例,该fragment才被置于由宿主activity管理的后台栈。
<?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>
//**注意每个fragment都需要一个唯一的表示**
②.通过编码将fragment添加到已存在的ViewGroup中
FragmentManager fragmentManager = getFragmentManager()
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
4.添加物界面的fragment
可以使用fragment为activity提供后台动作,却不需要实现这个方法。为无界面的字符串提供标签。可以通过findFragmentByTag()获取标签。
用android:tag属性提供一个唯一的字符串。。
5.管理Fragments
调用getFragmentManager()获得。
使用FragmentManager 可以做如下事情,包括:
使用findFragmentById()(用于在activity布局中提供有界面的fragment)或者findFragmentByTag()获取activity中存在的fragment(用于有界面或者没有界面的fragment)。
使用popBackStack()(模仿用户的BACK命令)从后台栈弹出fragment。
使用addOnBackStackChangedListener()注册一个监听后台栈变化的监听器
调用commit()并不立刻执行事务,相反,而是采取预约方式,一旦activity的界面线程(主线程)准备好便可运行起来。
6.创建Activity事件回调函数
在一些情况下可能需要fragment与activity共享事件。这样做的一个好方法是在fragment内部定义一个回调接口,并需要宿主activity实现它。
public interface OnArticleSelectedListener{
public void setOnArticleSelected(Uri articleUri);
}
private OnArticleSelectedListener mOnArticleSelectedListener;
public void setOnArticleSelectedListener(OnArticleSelectedListener onArticleSelectedListener){
mOnArticleSelectedListener = onArticleSelectedListener;
}
1144

被折叠的 条评论
为什么被折叠?



