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

Android Fragment 入門(一):把 Fragment 掛到 Activity 上的兩種寫法

編輯:關於 Android 程式設計

做 Android 的人對 Activity 應該都不陌生,幾乎每一個畫面都由它撑起。但 Activity 用久了就會碰到天花板:同一套版面配置在手機上比例剛好,換到平板這種大螢幕裝置上,往往會出現控制項被過度拉長、間距空得難看、資訊密度失衡等問題。

比較理想的做法,是把畫面切成幾個可重複使用、各自擁有獨立配置的「小方塊」,再依螢幕大小自由組合——這正是 Fragment 存在的理由。

一、Fragment 到底是什麼

官方對 Fragment 的定義是:Activity 介面中的一部分,或是一段可獨立描述的操作行為。你可以把多個 Fragment 拼在同一個 Activity 裡,組出多面板的複合介面;同一個 Fragment 也能被不同 Activity 重複使用。把它理解成「模組化的一段 Activity」會比較好懂:它有自己的生命週期、會收到屬於自己的事件,並且在 Activity 執行期間可以被動態加入或移除。

不過 Fragment 無法單獨存活,一定要依附在 Activity 之上,生命週期也完全被宿主 Activity 牽制:Activity 暫停,底下所有 Fragment 一起暫停;Activity 銷毀,Fragment 也一起消失。只有在 Activity 處於活躍狀態(onResume() 之後、onPause() 之前)時,你才能針對個別 Fragment 下指令。

更實用的是:每一次針對 Fragment 的操作都可以被包成一筆「事務」,塞進由 Activity 管理的 back stack。有了這個堆疊,就能反向回放這些事務,等於在 Fragment 層級支援了返回鍵的導航行為。

把 Fragment 放進 Activity 有兩條路:直接在 layout XML 中以 <fragment> 標籤宣告,或者在程式碼中建立 Fragment 實例後塞進指定的 ViewGroup。要注意的是,Fragment 並不一定非要佔據畫面,它也可以完全不提供 UI,只在背景替 Activity 辦事。

設計思路:一個介面,兩種形態

Android 3.0 正式引入 Fragment(碎片)概念,就是為了讓同一份程式碼能同時服務平板與手持裝置。官方示意圖把這件事講得很清楚:

(下圖左側為平板,右側為手持裝置)

二、Fragment 的生命週期

由於 Fragment 必須寄生在 Activity 之中,兩者的生命週期是綁在一起的:

  • Activity 暫停 → 其中所有 Fragment 都暫停;
  • Activity 進入 stopped → 其中所有 Fragment 都無法再被啟動;
  • Activity 被銷毀 → 其中所有 Fragment 一併銷毀。

而當 Activity 活躍時,你就能獨立控制 Fragment 的狀態,例如加上或移除。進行 fragment transaction 時,可以選擇把整筆事務存進 back stack,讓使用者得以回退。

使用 Fragment 需要繼承 Fragment 或其子類(DialogFragment、ListFragment、PreferenceFragment、WebViewFragment),所以程式碼風格與 Activity 相當接近。每建立一個 Fragment,起碼要關注三個回呼:

  • onCreate():系統建立 Fragment 時呼叫,適合在這裡初始化那些即使被暫停或停止也仍要保留的元件。
  • onCreateView():首次繪製 UI 時呼叫,需回傳一個 View;若 Fragment 不提供介面,回傳 null 即可。若你繼承的是 ListFragment,預設實作已經會回傳一個 ListView,不必自己寫。
  • onPause():使用者離開 Fragment 時第一個被呼叫的方法,該存的狀態要趁這裡存起來,因為使用者很可能不會再回來。

掛載 Fragment 到 Activity 有兩種方式:寫在版面配置檔裡,或在程式碼中動態掛載。前者簡單但缺乏彈性,後者才是真正能在執行期控制 Fragment 的方法。

三、方式一:寫進版面配置檔(不建議)

先準備一個平板模擬器,建立新專案,然後新增 fragment_hello.xml 與 HelloFragment.java。

Fragment 自己的配置檔:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="請輸入內容"/>
    <RatingBar
        android:id="@+id/ratingBar1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

Fragment 類別:

package com.example.m01_fragment01;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class HelloFragment extends Fragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_hello, null);
        return view;
    }

    @Override
    public void onPause() {
        super.onPause();
    }
}

關鍵就是 onCreateView() 中的 inflate():把自己的配置檔拉進來變成 View。第二個參數在沒有要掛載的父容器時,傳 null 就好。

另外提醒一個容易踩的坑:如果你的 minSdk 在 Android 4.0 以上,import 時要選 android.app.Fragment,而不是 support 套件裡的那個。

接著把 Fragment 宣告進 Activity 的配置:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <fragment
        android:id="@+id/fragment_hello"
        android:name="com.example.m01_fragment02.HelloFragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

android:name 要填你自己寫的 Fragment 完整類別路徑,這是整段配置的核心。系統在解析這個配置檔時,會自動把每個 <fragment> 具現化,呼叫它們的 onCreateView() 取得 View,再插入標籤所在的位置。跑起來畫面就會出現你的 Fragment 內容。

問題也很明顯:這種寫法把 Fragment 和 Activity 的視圖樹綁死了,執行期完全無法切換,所以實務上很少這麼做。

四、方式二:在程式碼中動態掛載(推薦)

下面做個小實例:點擊左側 Fragment 的按鈕,右側就彈出一個 Fragment。

(1)先把 Activity 的版面切成左右兩塊,左 1/4、右 3/4:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="horizontal" >

    <LinearLayout
        android:id="@+id/left"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:layout_weight="1"
        android:background="#00BFFF" >
        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="顯示"/>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/right"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="3"
        android:background="#00FFFF"
        android:orientation="vertical" >
    </LinearLayout>
</LinearLayout>

這裡每個 LinearLayout 都代表一個 Fragment 的容器,務必幫每個容器配一個 id,後面 transaction 要靠它定位。

(2)建立右側的 Fragment,配置檔 fragment_right.xml 放一個文字與一個按鈕:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="新聞內容" />
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />
</LinearLayout>

類別 RightFragment.java 的骨架和前面一樣,重點是在 onCreateView() 裡把按鈕接上監聽器,點下去跳一則 Toast:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_right, null);
    Button button = (Button) view.findViewById(R.id.button2);
    button.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(getActivity(), "我是fragment", Toast.LENGTH_SHORT).show();
        }
    });
    return view;
}

兩個細節別漏掉:findViewById 前面一定要有 view.,否則會找不到控制項;Toast 的第一個參數固定用 getActivity(),這樣才能拿到宿主 Activity 的 Context。

(3)在 Activity 中掛載 Fragment,監聽器部分如下:

button.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        // 步驟一:取得 FragmentTransaction 實例
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();

        // 步驟二:用 add() 把 Fragment 放進容器
        RightFragment rightFragment = new RightFragment();
        transaction.add(R.id.right, rightFragment);

        // 步驟三:commit() 讓異動生效
        transaction.commit();
    }
});

這三步驟請務必記牢:拿 FragmentManager → beginTransaction() → add()/remove()/replace() → commit()。

其中 add() 的第一個參數是容器視圖的資源 ID,不是 layout 的 ID,別搞混。這個 ID 有兩個作用:一是告訴 FragmentManager 該把 Fragment 的視圖摆在 Activity 視圖的哪個位置,二是作為 FragmentManager 佇列中該 Fragment 的唯一識別碼。

靈活性差別就在這裡:寫在 XML 裡的 Fragment 一上場就定錘,而透過 transaction 動態掛載的 Fragment,可以隨時加、隨時移除、隨時替換,也能進 back stack 支援返回鍵。

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