Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android Fragment 使用教學:兩種嵌入方式完整解析

編輯:關於 Android 開發

Fragment 通常是宿主 Activity 使用者介面的一部分,它會作為整個 view 階層的一員被嵌入到 Activity 之中。要把 fragment 加入 Activity 的版面配置,主要有兩種做法,以下分別說明。

一、在 Activity 的版面配置檔中宣告 fragment

你可以像設定一般 View 那樣,為 fragment 指定 layout 屬性(SDK 3.0 之後支援)。下面的例子是一個含有兩個 fragment 的 Activity:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
  3.      android:orientation="horizontal"
  4.      android:layout_width="match_parent"
  5.      android:layout_height="match_parent">
  6.      <fragment android:name="com.example.news.ArticleListFragment"
  7.              android:id="@+id/list"
  8.              android:layout_weight="1"
  9.              android:layout_width="0dp"
  10.              android:layout_height="match_parent" />
  11.      <fragment android:name="com.example.news.ArticleReaderFragment"
  12.              android:id="@+id/viewer"
  13.              android:layout_weight="2"
  14.              android:layout_width="0dp"
  15.              android:layout_height="match_parent" />
  16.    </LinearLayout>

其中 <fragment> 標籤的 android:name 屬性,指定了在版面配置中要具現化的 Fragment 類別。

當系統建立這個 Activity 的版面時,它會逐一具現化配置檔中指定的每個 fragment,並呼叫各自的 onCreateView() 方法來取得對應的版面,然後把 fragment 回傳的 View 直接插入到 <fragment> 元素所在的位置。

注意:每個 fragment 都需要一個唯一的識別碼。如此一來,當 Activity 重啟時,系統才能用它來還原 fragment(而你也可以用它來擷取 fragment 以處理某些事務,例如將它移除)。

為 fragment 提供識別碼有三種方式:

為 android:id 屬性指定一個唯一 ID;
為 android:tag 屬性指定一個唯一字串;
若兩者都未提供,系統會改用容器 view 的 ID。

二、使用 FragmentManager 將 fragment 加入既有的 ViewGroup

在 Activity 運行的任何時刻,你都可以把 fragment 加入它的版面配置,只需指定一個用來放置 fragment 的 ViewGroup 即可。要在 Activity 中操作 fragment 事務(例如新增、移除或替換 fragment),就必須使用 FragmentTransaction 提供的 API。

可以透過下面的方式,從 Activity 取得一個 FragmentTransaction 的執行個體:

FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

接著就能用 add() 方法加入 fragment,並指定要加入的 fragment 以及要插入的 view:

ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();

add() 的第一個參數,是 fragment 要放入的 ViewGroup(以 resource ID 指定);第二個參數則是要加入的 fragment。一旦透過 FragmentTransaction 做了變更,就必須呼叫 commit() 才能讓改動真正生效。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved