標籤:containe hid var 使用者輸入 asm 方法 回調 split activity
片段是為了給大螢幕(比如平板電腦)提供更加靈活的UI支援。可以把它看作是子活動,必須嵌在活動中,並且有自己的生命週期,能接收自己的使用者輸入事件。當把片段作為活動布局的一部分添加時,片段會定義自己的視圖布局。如何在活動的布局檔案中添加片段呢?通過標籤把片段作為活動的一個組件。
應該把每個片段都設計成可複用的模組化組件,避免直接從某個片段操縱另一個片段,這樣可以把一個片段加入到多個活動中去。模組化組件使得根據螢幕大小自適應選擇單視窗UI還是多視窗UI成為可能。以新聞應用為例,對平板可以在一個活動中添加列表片段和內容片段,而在手機中,一個活動中只有列表片段,點擊之後出現包含內容片段的活動。
建立片段
片段類
自訂片段必須繼承自Fragment。建立片段一般至少實現以下生命週期方法:
onCreate():系統在建立片段時調用此方法。應該在此方法中初始化想在片段暫停或者停止後恢複時保留的組件。
onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState):此方法為片段載入其布局檔案,系統在需要繪製片段布局時調用此方法。
參數:
inflater:用於載入布局檔案
container:片段布局將要插入的父ViewGroup,即活動布局。
savedInstanceState:在恢複片段時,提供上一片段執行個體相關資料的Bundle
樣本
public static class ExampleFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.example_fragment, container, false); }}
- onPause():應該在此方法內確認使用者會話結束後仍然有效任何更改。
向活動中添加片段
<?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>
當系統建立此布局時,會執行個體化在布局中指定的每個片段,並為每個片段調用onCreateView()方法,以載入每個片段的布局。系統會以返回的View來替代< fragment >元素。
- 方法二:在源碼中動態將片段添加到某個現有ViewGroup中
要想在活動中執行片段事務,如添加、刪除、替換片段,必須使用FragmentTransaction:
FragmentManager fragmentManager = getFragmentManager();FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
添加片段:
ExampleFragment fragment = new ExampleFragment();fragmentTransaction.add(R.id.fragment_container, fragment);#第一個參數為片段插入到的視圖fragmentTransaction.commit();
和活動之間通訊
在片段類中可以通過getActivity()得到和片段關聯的活動執行個體;
在活動類中可以通過FragmentManager.findFragmentById()擷取片段執行個體:
ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);
片段的生命週期
片段的生命週期和活動的生命週期類似,最大區別在於活動停止時會被放入由系統管理的活動返回棧中,而片段在移除事務執行期間,需要顯式調用addToBackStack(),片段才會放入由活動管理的返回棧。
除了和活動一樣的生命週期回調方法,片段還有幾個額外的回調方法:
onAttach():在片段與活動關聯時調用;
onCreateView():為片段建立視圖時調用
onActivityCreated():在活動的onCreate()方法已經返回時調用
onDestroyView():與片段關聯的視圖被移除時調用
onDetach():取消片段與活動的關聯時調用。
Android開發——UI_片段