Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android Fragment 的兩種使用方式

一般情況下,Fragment 會作為宿主 Activity 介面的一部分,被嵌進 Activity 完整的檢視階層裡。把 Fragment 放進 Activity 版面,主要有兩條路可走。

方式一:在版面檔中直接宣告

你可以像宣告 View 那樣,在 XML 裡為 Fragment 指定版面屬性(需 SDK 3.0 以上)。以下是一個含兩個 Fragment 的 Activity 例子:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:Android="https://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>

<fragment> 標籤上的 android:name 指定了要在版面中具現化的 Fragment 類別。

系統在建立這個 Activity 版面時,會逐一具現化配置中宣告的 Fragment,並呼叫各自的 onCreateView() 取得對應版面,接著把 Fragment 回傳的 View 直接插入到 <fragment> 元素所在的位置。

注意:每個 Fragment 都需要一個唯一標識,如此 Activity 重啟時系統才能用來恢復它,你自己也能靠它抓取 Fragment 來處理事務(例如移除)。

提供標識有三種做法:

  • 給 android:id 一個唯一 ID。
  • 給 android:tag 一個唯一字串。
  • 兩者都不給時,系統會沿用容器 View 的 ID。

方式二:用 FragmentManager 掛到既有 ViewGroup 上

Activity 執行期間的任何時刻,你都能把 Fragment 加進版面,只要指定一個用來承接它的 ViewGroup 即可。而要對 Fragment 做加、移除或替換這類事務操作,就必須使用 FragmentTransaction 提供的 API。

取得 FragmentTransaction 實例的寫法:

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

接著呼叫 add(),帶入要加入的 Fragment 以及插入位置:

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

add() 的第一個參數是以資源 ID 指定的目標 ViewGroup,第二個參數才是要加入的 Fragment。透過 FragmentTransaction 做完改動後,一定要呼叫 commit() 才能讓變化真正生效。

更多Android相關信息見Android 專題頁面 https://www.linuxidc.com/topicnews.aspx?tid=11

Copyright © Linux教程網 All Rights Reserved