onCreateView() :建立視圖java
onActivityCreate():activity建立完成的時候調用android
onDestoryView():銷燬視圖app
onDetach():與activity解除綁定ide
2.1 繼承fragment(android.app.Fragment)佈局
2.2 直接在佈局文件中使用spa
<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>
步驟:code
1.建立fragmentxml
2.經過getFragmentManager()方法獲得FragmentManagerblog
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()
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; }