1.對父activity附加和分離fragments分別經過onAttach和onDetach java
fragment/activity 到了pause狀態,onDetach是有可能不被調用就掛了,由於父activity的進程可能由於資源緊張被殺死。(意外死亡) android
onAttach通常是用來獲取對父activity的引用。(由於你可能須要用到父activity來初始化你的一些東西) 佈局
2.建立和銷燬Fragments 動畫
與activity同樣,你應該使用onCreate方法去初始化你的fragments。(onCreate方法在整個生命週期只執行1次)。 ui
注意:不像activity,fragment的ui初始化可不在onCreate方法中,而是onCreateView. code
若是fragment須要與父activtiy的UI交互,那麼你須要等onActivityCreate方法觸發才能夠,由於這個方法意味着你的activity已經完整初始化好了。 xml
3.Fragment狀態 生命週期
再次強調,fragment的命運與activity是息息相關的。所以,fragment的狀態經常要去參考activity的狀態,由於要保持一致。 隊列
當activities獲取到焦點,那麼它所含的fragments也能獲取到焦點。當activity暫停或者中止,fragments也暫停或者中止 。。。。。等等,當activity死掉了,fragment必須死。 進程
4.Fragment Manager
每一個activity包含一個fragment manager去管理它所包含的fragments. 你能夠獲取fragment manager經過getFragmentManager方法。
FragmentManager fragmentManager = getFragmentManager()
FragmentManager提供方法去獲取和使用Fragments和執行Fragment事務:增長,移除,或者代替Fragments.
1.增長Fragments到Activities
最簡單的方式,固然XML嘍,直接例子不解釋了:(tag或者id是必須給一個的,便於後期查找,也便於activity重啓的時候系統用來恢復)
<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.paad.weatherstation.MyListFragment」 android:id=」@+id/my_list_fragment」 android:layout_width=」match_parent」 android:layout_height=」match_parent」 android:layout_weight=」1」 /> <fragment android:name=」com.paad.weatherstation.DetailsFragment」 android:id=」@+id/details_fragment」 android:layout_width=」match_parent」 android:layout_height=」match_parent」 android:layout_weight=」3」 /> </LinearLayout>
5.使用Fragment事務:
事務能夠用來增長,移除,替換Fragments. 使用事務可使你的佈局動態化,能夠基於用戶的交互和APP的狀態作適應和改變。它們還支持指定顯示的過渡動畫和是否去包含事務在Back Stack。
使用beginTransaction一個新的Fragment事務(FragmentManager的方法)。若是須要,在你設置顯示的動畫前,可使用add,remove,replace方法修改佈局和設置合適的back-stack行爲。當你準備好改變的時候,使用commit去提交到UI隊列中。
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// Add, remove, and/or replace Fragments.
// Specify animations.
// Add to back stack if required.
fragmentTransaction.commit();
增長、移除或者代替Fragments:
add:
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.ui_container, new MyListFragment());
fragmentTransaction.commit();
注意!!!:fragment沒視圖時,你只能指定tag(add(Fragment fg,String tag)),若是有視圖,tag和id均可以。
首先必須明白,既然是動態添加的,我怎麼知道該加到佈局的哪部分,因此這裏要指定父佈局容器的ID,R.id.ui_container。
remove:
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment fragment = fragmentManager.findFragmentById(R.id.details_fragment);
fragmentTransaction.remove(fragment);
fragmentTransaction.commit();
replace:
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.ui_container, new DetailFragment(selected_index)); //還有個重載方法,能夠爲新的fragment指定tag fragmentTransaction.commit(); //這裏也解釋爲何無視圖的不能有id,沒有視圖哪來的父容器? 因此也不能findFragmentByID