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

Android Fragment 入門:三個步驟完成動態切換

編輯:關於 Android 程式設計

Fragment 是 Android 3.0 才引入的 API,最初的設計目的是為了適配大螢幕平板——把介面拆成幾個可重複組合的區塊,讓同一套程式碼在手機與平板上都能有合理呈現。你可以把 Fragment 理解為 Activity 的一個「片段」或子模塊。本文示範最基礎的用法:建立 Fragment 並在 Activity 中切換顯示。

一、建立主布局

布局分左右兩欄:左側是三個按鈕用來切換 Fragment,右側用 FrameLayout 作為 Fragment 的容器。

<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="${relativePackage}.${activityClass}">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <Button
            android:id="@+id/bt_1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="red"
            android:text="Fragement1" />

        <Button
            android:id="@+id/bt_2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="green"
            android:text="Fragement2" />

        <Button
            android:id="@+id/bt_3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="blue"
            android:text="Fragement3" />
    </LinearLayout>

    <FrameLayout
        android:id="@+id/fl"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />

</LinearLayout>

這裡有個細節值得留意:FrameLayout 的寬度設為 0dp 搭配 layout_weight="1",讓它自動吃掉剩餘空間。直接用 match_parent 反而容易把左側按鈕擠不見。

二、繼承 Fragment 建立子類

每個 Fragment 都要有一個對應的布局檔,所以這裡需要三個 Fragment 類別與三個布局檔。

public class Fragement01 extends Fragment {
    // 回傳的 View 會作為 Fragment01 的內容顯示在界面上
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragement1, null);
    }
}
public class Fragement02 extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragement2, null);
    }
}
public class Fragement03 extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragement3, null);
    }
}

三個布局檔各自只用不同底色與文字做區隔,方便確認切換是否生效:

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="這是 Fragement1"
        android:textSize="25sp" />
</LinearLayout>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#00FF00"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="這是 Fragement2"
        android:textSize="25sp" />
</LinearLayout>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#0000FF"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="這是 Fragement3"
        android:textSize="25sp" />
</LinearLayout>

三、在 Activity 中切換

public class MainActivity extends Activity {

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

    public void red(View v) {
        replaceFragment(new Fragement01());
    }

    public void green(View v) {
        replaceFragment(new Fragement02());
    }

    public void blue(View v) {
        replaceFragment(new Fragement03());
    }

    /**
     * Fragment 切換的標準五步:
     * 1. 取得 Fragment 實例
     * 2. 取得 FragmentManager
     * 3. 開啟事務
     * 4. 執行 replace
     * 5. 提交
     */
    private void replaceFragment(Fragment fragment) {
        FragmentManager fManager = getFragmentManager();
        FragmentTransaction ft = fManager.beginTransaction();
        ft.replace(R.id.fl, fragment);
        ft.commit();
    }
}

把重複的流程抽成一個方法後,程式碼立刻清爽許多——三個按鈕的點擊事件各自只剩一行。

執行結果:

補充說明

為什麼要有 Fragment。手機上通常一屏顯示一個區塊,而平板上可以左右並置。若把每個區塊都做成獨立 Activity,就得為平板再寫一套程式;改用 Fragment 後,只需調整容器布局即可複用同一批元件。

replace 與 add 的差別。replace() 會移除容器內既有 Fragment 再放入新的;add() 則是疊加上去。若希望返回鍵能回到上一個 Fragment,記得在 commit 之前呼叫 ft.addToBackStack(null)。

getFragmentManager 與 getSupportFragmentManager。前者是 API 11 之後的原生版本,後者屬於 support-v4 套件。專案若需相容舊版系統,應改用 support 套件中的 Fragment 類別與對應的 Manager,兩者不可混用。

總體來說,Fragment 的入門步驟就是這幾個,記牢流程之後就能靈活應用了。

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