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

Fragment 的真正的用場:執行時動態加入

編輯:Android 開發教學

Fragment 真正的價值在於能在程式執行過程中動態加入,而不是只寫死在版面檔裡。

一、新建專案

二、res/layout/main.xml

作為容器的版面故意留空,因為 Fragment 稍後才會被塞進來:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >
</LinearLayout>

三、res/layout/fragment1.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#00FF00"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/lblFragment1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="This is fragment #1"
        android:textColor="#000000"
        android:textSize="25sp" />
</LinearLayout>

四、res/layout/fragment2.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFFE00"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="This is fragment #2"
        android:textColor="#000000"
        android:textSize="25sp" />
</LinearLayout>

五、Fragment1.java

public class Fragment1 extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // --- Inflate the layout for this fragment ---
        return inflater.inflate(R.layout.fragment1, container, false);
    }
}

六、Fragment2.java

public class Fragment2 extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // --- Inflate the layout for this fragment ---
        return inflater.inflate(R.layout.fragment2, container, false);
    }
}

七、在 Activity 中動態加入

關鍵是 FragmentTransaction,而容器必須先有版面,才能作為掛載點:

FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.container, new Fragment1());
ft.addToBackStack(null);
ft.commit();

這裡有三個細節容易出錯。第一,inflate 的第三個參數必須是 false——若傳 true,Fragment 會直接把 container 當成自己的父容器並掛上去,之後 Activity 再 add 一次就會出問題。第二,add 的容器 id 要指向 main.xml 中實際存在的檢視,若那個位置沒有元件就會拋出例外,因此實務上通常放一個 FrameLayout 當佔位。第三,commit 是異步的,呼叫後不能立刻假設畫面已更新;需要保證順序時應改用 commitNow 或在 commit 後透過 executePendingTransactions() 強制執行。

最後提醒:本範例使用 getFragmentManager(),這是 framework 內建的版本;若專案使用 support-v4 或 AndroidX,應改用 getSupportFragmentManager(),兩者不可混用。

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