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

Fragment 的兩種添加方式:XML 靜態聲明與代碼動態加載

編輯:關於 Android 開發

Fragment 的兩種添加方式:XML 靜態聲明與代碼動態加載

Fragment 可以理解為 Activity 界面中的一個「行為單元」或界面片段。借助 Fragment,你可以在同一個 Activity 裡拼裝出多塊區域的複合界面,也可以讓同一個 Fragment 在多個 Activity 之間反覆使用。把它想成 Activity 的模塊化零件會更好理解:它擁有自己的生命週期,能接收並處理自己的輸入事件,還能在 Activity 運行期間被靈活地添加或移除。

兩個關鍵概念:Fragment 與宿主

Fragment 不能獨立存在,它的生命週期直接受宿主 Activity 的牽制。Activity 一旦進入 paused 狀態,內部所有 Fragment 同步暫停;Activity 被銷毀,其中的 Fragment 也隨之銷毀。

Fragment 的概念自 Android 3.0(API 11)開始引入。有了它,你不必再手動追蹤整個視圖體系的複雜變化——把 Activity 的布局切成若干 Fragment,就能在運行時改寫界面呈現,而這些改動會被保存在 Activity 管理的回退棧裡。

如何實現一個 Fragment

要創建 Fragment,必須繼承 Fragment 類(或其子類)。Fragment 的代碼結構與 Activity 幾乎一致,同樣擁有 onCreate()、onStart()、onPause()、onStop() 這類回調。因此,如果你正在把一個老項目改造成 Fragment 架構,最省事的做法就是把 Activity 各回調裡的邏輯,對應搬遷到 Fragment 的同名回調中。

除基類 Fragment 外,官方還提供了幾個常用子類,可以按需繼承:

DialogFragment、ListFragment、PreferenceFragment

必須優先實現的生命週期方法

onCreate():Fragment 被創建時由系統調用。適合在這裡初始化那些需要在 Fragment 暫停或停止後仍然保留的組件。

onCreateView():首次為 Fragment 繪製界面時調用,必須返回該 Fragment 的根 View。若 Fragment 沒有界面,返回 null 即可。

onPause():用戶即將離開 Fragment 的第一個信號(並不總意味著銷毀)。凡是需要持久化的改動,通常都應該在這裡落盤,因為用戶有可能不再回來。

把 Fragment 添加到 Activity 的兩種途徑

(1)在 Activity 布局文件中直接聲明

(2)通過 Java 代碼添加到既有的 ViewGroup 中

下面用一個左右分欄的例子演示兩種做法,用兩種不同底色區分兩個 Fragment:

方式一:在布局文件中聲明 Fragment

我們直接在主布局 activity_main.xml 裡聲明左右兩個 Fragment,即可完成上圖的展示效果。

第一步:編寫左右兩側的內容布局 left_layout.xml 與 right_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:background="#6f6669">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="潘侯爺"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="碧空海"/>
</LinearLayout>

第二步:建立與布局對應的 Fragment 子類 LeftFragment.java / RightFragment.java

LeftFragment.java:

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

public class LeftFragment extends Fragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // 透過 inflater 把 XML 布局翻譯成 View 對象
        View view = inflater.inflate(R.layout.left_layout, container, false);
        return view;
    }

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

第三步:在主布局 activity_main.xml 中聲明兩個 Fragment

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:context="com.example.administrator.fragmenttest.MainActivity">
    <fragment
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:name="com.example.administrator.fragmenttest.LeftFragment"
        tools:layout="@layout/left_layout" />
    <fragment
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="3"
        android:name="com.example.administrator.fragmenttest.RightFragment"
        tools:layout="@layout/right_layout" />
</LinearLayout>

關鍵在於 android:name 指定 Fragment 的全限定類名,而 tools:layout 只是讓 Android Studio 在預覽窗口裡渲染出效果,並不影響運行時行為。

方式二:通過代碼把 Fragment 添加到已有的 ViewGroup

接下來演示如何把右側的 right_layout 用代碼塞進主布局的容器裡。

先看需要掌握的知識點。管理 Activity 中的 Fragment 離不開 FragmentManager,在 Activity 中調用 getFragmentManager() 即可獲得。它能做的事情包括:

1. 用 findFragmentById()(適合布局中帶界面的 Fragment)或 findFragmentByTag() 取得已存在的 Fragment 實例。

2. 用 popBackStack() 模擬用戶按下返回鍵,把 Fragment 從回退棧彈出。

3. 用 addOnBackStackChangedListener() 註冊回退棧變化監聽器。

在 Activity 中使用 Fragment 的一大特色,就是能響應用戶操作完成添加、刪除、替換等動作。每一組提交給 Activity 的變化被稱為一次「事務(Transaction)」,由 FragmentTransaction 的 API 統一處置。

第一步:主布局 activity_main2.xml(左側仍在 XML 中聲明,右側預留 FrameLayout 容器)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:id="@+id/activity_main2"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:context="com.example.administrator.fragmenttest.Main2Activity">
    <fragment
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:name="com.example.administrator.fragmenttest.LeftFragment"
        tools:layout="@layout/left_layout" />
    <FrameLayout
        android:id="@+id/right"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="3"></FrameLayout>
</LinearLayout>

第二步:在 Main2Activity.java 中用代碼完成填充

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class Main2Activity extends AppCompatActivity {
    FragmentManager fragmentManager;
    FragmentTransaction fragmentTransaction;
    RightFragment rightFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        // 取得 FragmentManager,用於管理 ViewGroup 中的 Fragment
        fragmentManager = getFragmentManager();

        // 開啟一個事務,後續所有操作都在這個事務裡完成
        fragmentTransaction = fragmentManager.beginTransaction();

        // 實例化待管理的 Fragment
        rightFragment = new RightFragment();

        // 以事務方式把 Fragment 添加到容器
        fragmentTransaction.add(R.id.right, rightFragment);

        // 事務必須提交才會生效
        fragmentTransaction.commit();
    }
}

兩種方式各有適用場景:布局聲明寫起來最省事,但 Fragment 一旦加入便難以在運行時替換;代碼方式則給出了完全的動態控制權。Fragment 與 Activity 之間的通信,我們留到後續文章中再細細展開。

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