1.生命周期
onCreateView() :创建视图
onActivityCreate():activity创建完成的时候调用
onDestoryView():销毁视图
onDetach():与activity解除绑定
2.静态使用
2.1 继承fragment(android.app.Fragment)
2.2 直接在布局文件中使用
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"> <fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/fragment1"
android:name="example.com.fragmentdemo.OneFragment"
/> </RelativeLayout>
3.动态使用
步骤:
1.创建fragment
2.通过getFragmentManager()方法得到FragmentManager
3.开启一个事务,beginTransaction()
4.添加、移除、替换、隐藏、显示fragment,add/remove/replace/hide/show
5.提交事务,commit();
manager.beginTransaction().add(R.id.fl,twoFragment).commit();
如果要实现类似于返回栈的效果,在commit()前 调用addToBackStack()方法
manager=getFragmentManager();
manager.beginTransaction().add(R.id.fl,twoFragment).addToBackStack(null).commit();
replace()方法会使fragment视图销毁 执行onpause()/onStop()/onDestoryView()
remove()方法会使fragment销毁 执行onpause()/onStop()/onDestoryView()/onDesdory()/onDecath()
hide()/show()不会执行其他的生命周期
锁屏 onPause()/onStop() 锁屏恢复:onStart()/onResume()
4.携带数据
1.在Fragment中创建newInstance方法,使Fragment携带参数
public static OneFragment newInstance(String txt){
OneFragment oneFragment=new OneFragment();
Bundle bundle=new Bundle();
bundle.putString("param",txt);
oneFragment.setArguments(bundle);
return oneFragment;
}
2.声明Fragment
oneFragment=OneFragment.newInstance("oneFragment");
3.在Fragment的onCreateView()中获取参数
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
Log.d(TAG, "onCreateView: ");
View view=inflater.inflate(R.layout.fragment_one,container,false);
if(getArguments()!=null){
Bundle bundle=getArguments();
String str= bundle.getString("param");
Log.e("OneFragment","onCreateView(OneFragment.java:48):"+str);
}
return view;
}