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

Android Fragment 入門:靜態宣告與動態建立一次學會

編輯:關於 Android 開發

Fragment 是 Activity 介面中的一部分或一種行為。可以把多個 Fragment 組合到一個 Activity 中,構成多畫面介面,也能在不同 Activity 之間重用同一個 Fragment。把它想成「模組化的一段 Activity」:有自己的生命週期、會接收自己的事件,並可在 Activity 運行時被加入或移除。

Fragment 與 Activity 的關係

Fragment 不能獨立存在,必須嵌入 Activity,其生命週期直接受所屬 Activity 影響。例如 Activity 暫停時,它擁有的所有 Fragment 都會暫停;Activity 銷毀時,所有 Fragment 也被銷毀。

然而在 Activity 運行期間(onResume() 之後、onPause() 之前),可以自由操作每個 Fragment,例如新增或刪除。執行這類操作時可以把事務加入一個由 Activity 管理的堆疊,堆疊中每一筆都是 Fragment 的一次事務;有了這個堆疊,就能反向執行 Fragment 事務,於是在 Fragment 層級也能支援「返回」鍵的向後導航。

加入 Activity 時,Fragment 必須置於某個 ViewGroup 中,並定義自己的介面。既可以在 layout.xml 中用 <fragment> 標籤宣告,也可以在程式碼中建立後加入 ViewGroup。此外,Fragment 未必要佔據畫面,它也可以隱身在後台為 Activity 工作(例如執行資料查詢)。

實作一:靜態宣告

主版面配置直接用兩個 <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"
    android:orientation="horizontal"
    tools:context=".MainActivity" >

    <fragment
        android:id="@+id/fragment1"
        android:name="com.wuyudong.fragment.Fragment1"
        android:layout_width="0dip"
        android:layout_height="fill_parent"
        android:layout_weight="1" >
    </fragment>

    <fragment
        android:id="@+id/fragment2"
        android:name="com.wuyudong.fragment.Fragment2"
        android:layout_width="0dip"
        android:layout_height="fill_parent"
        android:layout_weight="1" >
    </fragment>
</LinearLayout>

接著在 layout 下新增兩個版面檔。fragment1.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:background="#0000ff"
    android:orientation="vertical" >
</LinearLayout>

fragment2.xml 結構相同,只換成另一個背景色。

再建立兩個 Java 檔:

public class Fragment1 extends Fragment {
    /** fragment 被建立時呼叫,回傳它要顯示的內容 */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment1, null);
    }
}

Fragment2.java 同理。執行後畫面會左右並排兩塊不同顏色的區域。


實作二:動態建立

在同一個專案基礎上,把 activity_main.xml 中的兩個 <fragment> 段落刪掉,其他不動。接著在 MainActivity 中加入:

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 1. 判斷目前手機的方向
        int width = getWindowManager().getDefaultDisplay().getWidth();
        int height = getWindowManager().getDefaultDisplay().getHeight();

        Fragment1 fragment1 = new Fragment1();
        Fragment2 fragment2 = new Fragment2();

        FragmentManager fm = getFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();

        if (width > height) {
            // 水平方向顯示 Fragment1
            ft.replace(android.R.id.content, fragment1);
        } else {
            // 垂直方向顯示 Fragment2
            ft.replace(android.R.id.content, fragment2);
        }
        ft.commit();
    }
}

這段程式碼示範了動態建立 Fragment 的典型套路:getFragmentManager() 取得管理者 → beginTransaction() 開啟事務 → replace() 指定容器與 Fragment → commit() 送出。它也是實作「依旋轉方向切換版面」最直白的做法。

補充:兩種方式的取捨

靜態宣告寫在 XML 裡,結構一目了然,但一旦加入就無法在執行期移除或替換,靈活性較低。動態建立則完全可控,能依 conditions 決定要放哪個 Fragment、要不要加入返回堆疊,代價是版面結構變得沒那麼直觀。實務上常見的折衷是:在 XML 中放一個 FrameLayout 當容器,其餘全部用動態方式處理。

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