Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android Fragment 入門完全指南(圖文)

編輯:Android 開發實例

Fragment 是什麼

Fragment 從 Android 3.0(API 11)開始引入。可以把 Fragment 想成 Activity 裡的一個模塊:它有自己的版面、自己的生命週期、能獨立處理輸入事件,並且在 Activity 執行期間可以被動態加入或移除。

這個設計最大的價值是複用與適配。同一個 Fragment 可以被多個 Activity 共用;當 App 同時要支援平板與手機時,也能靠 Fragment 做出彈性版面——平板上左右並排顯示列表與內容,手機上則分兩個頁面切換,邏輯共用同一套程式碼。

生命週期:與宿主 Activity 綁在一起

Fragment 無法獨立存在,必須依附在 Activity 上,因此它的狀態跟著宿主走:Activity 暫停,其中的 Fragment 一起暫停;Activity 停止,Fragment 無法啟動;Activity 被銷毀,Fragment 也隨之銷毀。

但在 Activity 處於活躍狀態時,可以獨立控制 Fragment 的狀態,例如動態加上或移除。進行這類 fragment transaction 時,還可以把 Fragment 放進 Activity 的回退堆疊,讓使用者按返回鍵回到上一個狀態。

怎麼開始寫

繼承 Fragment 或其子類(DialogFragment、ListFragment、PreferenceFragment、WebViewFragment),寫法與 Activity 相當類似。

Support Library 的準備。要在舊版本系統上使用 Fragment,需要引入 support-v4.jar,路徑是 <sdk>/extras/android/support/v4/android-support-v4.jar,它讓 API 4(Android 1.6)以上都能使用 Fragment。匯入方式:把 jar 複製到專案的 libs 目錄,然後右鍵專案 → Properties → Java Build Path → Add External JARs 加入。

使用 Support Library 時,import 要對應改成:

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;

同時宿主 Activity 要繼承 FragmentActivity 而不是 Activity。

三個必須實作的回呼

onCreate():系統建立 Fragment 時呼叫,用來初始化那些即使被暫停或停止也仍要保留的元件。

onCreateView():第一次繪製 UI 時呼叫,必須回傳一個 View;若 Fragment 不提供 UI,回傳 null 即可。特別注意,如果繼承的是 ListFragment,此方法的預設實作會回傳一個 ListView,就不必自己寫。

onPause():使用者離開 Fragment 時第一個被呼叫的方法。需要提交的變更應在此處理,因為使用者很可能不會再回來。

實作 Fragment 的版面

假設版面定義在 example_fragment.xml:

public static class ExampleFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // 把版面攤開成 View 並回傳
        return inflater.inflate(R.layout.example_fragment, container, false);
    }
}

inflate() 的三個參數分別是:資源 ID(對應的版面檔)、父容器(container 代表這個 Fragment 在 Activity 中的父檢視)、以及一個布林值表示是否要把這個版面直接掛到父容器上。這裡必須填 false——系統已經會自行插入,填 true 會多產生一層無用的 ViewGroup。

把 Fragment 放進 Activity 的兩種方式

方式一:寫在版面檔裡

直接用 <fragment> 標籤宣告,android:name 填 Fragment 的完整類名:

<?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 並呼叫其 onCreateView(),把結果插入標籤所在的位置。這種寫法的缺點是無法在執行期更換 Fragment。

為 Fragment 標示身份有三種方式:android:id(唯一 id)、android:tag(唯一字串),若兩者都沒給,系統會採用容器檢視的 id。

方式二:程式碼動態加入

Activity 執行中可以随时動態增減 Fragment,這也是 Fragment 真正的價值所在:

FragmentManager fragmentManager = getFragmentManager();
// 使用 support 套件時改為 getSupportFragmentManager()

FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

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

add() 的第一個參數是這個 Fragment 要放進去的容器 id,最後一定要呼叫 commit() 讓變更生效。

動手做:兩種方式各加一次

自訂 Fragment 類別(ExampleFragment.java)

package com.example.learningfragment;

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

public class ExampleFragment extends Fragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        System.out.println("ExampleFragment--onCreate");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        System.out.println("ExampleFragment--onCreateView");
        return inflater.inflate(R.layout.example_fragment_layout, container, false);
    }

    @Override
    public void onPause() {
        super.onPause();
        System.out.println("ExampleFragment--onPause");
    }

    @Override
    public void onResume() {
        super.onResume();
        System.out.println("ExampleFragment--onResume");
    }

    @Override
    public void onStop() {
        super.onStop();
        System.out.println("ExampleFragment--onStop");
    }
}

Fragment 的版面(example_fragment_layout.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:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/num1" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/num2" />
</LinearLayout>

宿主 Activity(LearnFragment.java)

package com.example.learningfragment;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

public class LearnFragment extends FragmentActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_learn_fragment);

        // 以程式碼方式加入 Fragment
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

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

Activity 的版面(activity_learn_fragment.xml)

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button android:id="@+id/btn1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/btn1" />

    <!-- 方式一:版面中直接宣告 -->
    <fragment
        android:name="com.example.learningfragment.ExampleFragment"
        android:id="@+id/fragment1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button android:id="@+id/btn2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/btn2" />

    <!-- 方式二:這個容器留給程式碼動態加入 -->
    <LinearLayout
        android:id="@+id/linear"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <Button android:id="@+id/btn3"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/btn3" />
    </LinearLayout>
</LinearLayout>

執行結果:

可以看到第二種方式加入時指定了父容器(一個線性版面)的 id,而該容器中原本已有一顆 Button 3,因此 Fragment 被放在它之後。

延伸資源

Fragment 類別文件:
https://developer.android.com/reference/android/app/Fragment.html
Training:Building a Dynamic UI with Fragments
https://developer.android.com/training/basics/fragments/index.html
Fragments Developer Guide:
https://developer.android.com/guide/components/fragments.html

最後補一句現況:AndroidX 推出之後,套件命名空間已從 android.support.v4 改為 androidx.fragment,且官方明確建議以 Fragment 取代 Activity 作為介面單元。新專案請直接採用 AndroidX 版本,並搭配 Navigation Component 管理 Fragment 的堆疊與切換,會比自己寫 FragmentTransaction 輕鬆許多。

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