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

Android Fragment 一篇搞懂:從靜態佈局到動態管理與通信

編輯:關於 Android 程式設計

提到 Android 的界面開發,Activity 幾乎是每個開發者最先接觸的知識點,相信大家都已經耳熟能詳,這裡就不再多費筆墨。

不過 Activity 也有天生的短板。同一套界面放到手機上或許恰到好處,一旦搬到屏幕碩大的平板上,問題就浮現出來了:界面被過度拉伸、控件之間的留白變得鬆散,觀感大打折扣。更好的做法是像搭積木一樣,在一個 Activity 裡嵌入多個「小 Activity」,並且讓每一塊都能擁有自己獨立的布局。這正是 Fragment(碎片)登場的舞台。

Fragment 初識

為了解決界面在平板上適配不佳的困擾,Android 從 3.0 版本開始引入了 Fragment 這一機制。它的形態與 Activity 頗為相似,同樣能夠承載自己的布局,只是通常依附在 Activity 之中運行。

不妨想象這樣一個場景:屏幕上並排著兩個 Fragment,Fragment 1 內部是一個 ListView,逐行列出書名;Fragment 2 則由 TextView 和 ImageView 組成,負責呈現某本書的詳細介紹與封面插圖。如此一來,平板寬敞的屏幕空間就被充分利用了起來。

需要留意的是,Fragment 是 3.0 版本才引入的。如果你維護的是 3.0 之前的舊項目,就必須先引入 android-support-v4 的 jar 包,才能正常使用了。

用 XML 靜態聲明 Fragment

新建一個名為 Fragments 的項目,接著在 layout 目錄下建立 fragment1.xml。這個布局非常樸素,一個 LinearLayout 裡放了一個 TextView:

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

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

依樣畫葫蘆,再寫一個 fragment2.xml,背景色換成 #ffff00,文字改為 This is fragment 2 即可。

隨後新建 Fragment1 類,讓它繼承自 Fragment,核心工作就是在 onCreateView 裡加載剛剛寫好的布局:

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

Fragment2 的寫法完全一致,只是加載的是 fragment2.xml。

接下來打開 activity_main.xml,在其中引入這兩個 Fragment。這裡要借助 android:name 前綴來指向具體的 Fragment 類,並用 layout_weight 讓它們平分屏幕:

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

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

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

最後的 MainActivity 幾乎不用動手,系統生成的默認代碼就足以把界面跑起來:

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

運行程序你會看到,一個 Activity 和諧地容納了兩個 Fragment,二者平分整個屏幕。

動態添加 Fragment

學會在 XML 裡寫 Fragment 只是入門。Fragment 真正的威力,在於能夠在應用運行時被動態地添加進 Activity,這也是界面能夠千變萬化的關鍵所在。

我們在上一節的基礎上改造。打開 activity_main.xml,把兩個 Fragment 的引用全部刪掉,只保留最外層的 LinearLayout,並給它一個 id,作為後續動態掛載的容器:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:baselineAligned="false">
</LinearLayout>

然後在 MainActivity 中根據屏幕方向決定加載哪個 Fragment:

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Display display = getWindowManager().getDefaultDisplay();
        if (display.getWidth() > display.getHeight()) {
            Fragment1 fragment1 = new Fragment1();
            getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment1).commit();
        } else {
            Fragment2 fragment2 = new Fragment2();
            getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment2).commit();
        }
    }
}

這段邏輯先取出屏幕的寬與高,寬大於高時加載 Fragment1,反之則加載 Fragment2。歸納起來,動態添加 Fragment 一共四步:

  1. 通過 Activity 的 getFragmentManager() 拿到 FragmentManager;
  2. 調用 beginTransaction() 開啟一個事務;
  3. 用 replace() 把 Fragment 實例放入指定容器,傳入容器 id 與 Fragment 實例;
  4. 調用 commit() 提交事務。

Fragment 的生命周期

和 Activity 一樣,Fragment 也有自己完整的生命周期。理解它是寫好 Fragment 的必修課。我們可以在每個回調方法裡打印日誌,直觀地觀察調用順序:

public class Fragment1 extends Fragment {
    public static final String TAG = "Fragment1";

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        Log.d(TAG, "onAttach");
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.d(TAG, "onCreateView");
        return inflater.inflate(R.layout.fragment1, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.d(TAG, "onActivityCreated");
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.d(TAG, "onStart");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "onResume");
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d(TAG, "onPause");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d(TAG, "onStop");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.d(TAG, "onDestroyView");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.d(TAG, "onDetach");
    }
}

跑一遍程序,對照日誌你就會發現,Fragment 的整體流程與 Activity 幾乎如出一轍,只是多了幾個 Activity 沒有的新方法,這幾個正是需要重點記憶的:

  • onAttach:Fragment 與 Activity 建立關聯時調用。
  • onCreateView:為 Fragment 加載布局時調用。
  • onActivityCreated:Activity 的 onCreate 執行完畢後調用。
  • onDestroyView:Fragment 的布局被移除時調用。
  • onDetach:Fragment 與 Activity 解除關聯時調用。

Fragment 之間的通信

一個 Activity 通常會同時容納多個 Fragment,那麼 Fragment 彼此之間如何互動就成了繞不開的問題。下面用一個例子演示:如何讓 Fragment 2 去讀取 Fragment 1 中的視圖內容。

首先在 fragment2.xml 裡加一個按鈕:

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

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

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get fragment1 text" />
</LinearLayout>

再給 fragment1.xml 的 TextView 補上一個 id:

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

接著在 Fragment2.java 的 onActivityCreated 裡處理按鈕點擊,通過 getActivity() 拿到所屬 Activity,再用 findViewById 找到 Fragment 1 的 TextView:

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

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Button button = (Button) getActivity().findViewById(R.id.button);
        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                TextView textView = (TextView) getActivity().findViewById(R.id.fragment1_text);
                Toast.makeText(getActivity(), textView.getText(), Toast.LENGTH_LONG).show();
            }
        });
    }
}

運行後點擊 Fragment 2 上的按鈕,Fragment 1 的文字便被成功讀出並以 Toast 彈出。這一切的關鍵就在 getActivity():它讓 Fragment 拿到關聯的 Activity,進而調用 Activity 的 findViewById,就能訪問到同一 Activity 下其他 Fragment 的視圖了。

至此,關於 Fragment 你該掌握的核心知識就齊全了。若想進一步動手實戰,可以延伸閱讀 Fragment 兼容手機與平板、以及用碎片替代 ActivityGroup 的相關主題。

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