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

Android 筆記(四):Fragment 的基本用法與 Activity 通訊

編輯:關於 Android 程式設計

前置說明一:照前面的方式建立專案時,如果用的是較新的 ADT,而 Minimum SDK 選了 Android 2.* 或 1.*,系統會自動產生一個相容用的附屬專案 appcompat_v7。這個專案不能刪,刪掉會報錯。

前置說明二:專案建立好之後,layout 資料夾中會預設有兩個檔案:activity 與 fragment 各一。

一、Fragment 是什麼

Fragment 直譯為「碎片、片段」,說白了就是一個可重複使用的模組。它的價值在於把「畫面的一部分」抽成獨立元件,讓同一塊 UI 能在不同 Activity 之間共用,也讓平板與手機能共用同一套邏輯。

可以這樣理解 Fragment 與 Activity 的關係:

Fragment 可以被多個 Activity 重用,它有自己的生命週期與版面,但必須依附在一個 Activity 之上才能顯示。Fragment 有自己的 onCreateView() 來產生自己的檢視,而 Activity 則負責決定「要把哪個 Fragment 放在畫面的哪個位置」。

二、Fragment 的版面檔

fragment_main.xml:一個文字與兩個按鈕。

<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="vertical"
    tools:context="com.javen.xresource.activity.fragment.MainFragment" >

    <TextView
        android:id="@+id/ftxv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/fragment" />

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/change_fragment" />

    <Button
        android:id="@+id/btn2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/change_activity" />

</LinearLayout>

三、Activity 的版面檔

activity_main.xml:自己有一個文字,並用 <fragment> 標籤把 Fragment 嵌進來。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.javen.xresource.activity.MainActivity"
    tools:ignore="MergeRootFrame">

    <TextView
        android:id="@+id/atxv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/activity" />

    <!-- 以 XML 方式在 Activity 中嵌入 Fragment -->
    <fragment
        android:name="com.javen.xresource.activity.fragment.MainFragment"
        android:id="@+id/mft"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

四、建立 MainFragment 類別

繼承 Fragment,重點在覆寫 onCreateView():用 inflater 把版面攤開成 View 並回傳。要注意的是,findViewById 必須在這裡產生的 rootView 上呼叫,而不是直接呼叫 Fragment 自己的方法。

package com.javen.xresource.activity.fragment;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.javen.xresource.activity.R;

public class MainFragment extends Fragment {

    private TextView fragmentTextView;
    private Button button;

    public MainFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // 使用 fragment_main.xml 初始化 Fragment
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);

        // 注意:要在 rootView 上找元件
        button = (Button) rootView.findViewById(R.id.btn);
        fragmentTextView = (TextView) rootView.findViewById(R.id.ftxv);

        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                fragmentTextView.setText("我被 fragment 點擊了...");
            }
        });

        return rootView;
    }
}

這樣 Fragment 部分就完成了。

五、MainActivity 的程式碼

package com.javen.xresource.activity;

import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

    private Button button;
    private TextView activityTextView;

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

        /* 也可以用 Java 程式碼嵌入 Fragment,效果與 XML 方式相同:
        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new MainFragment())
                    .commit();
        }
        */

        activityTextView = (TextView) findViewById(R.id.atxv);

        // 取得 Activity 中的 Fragment
        Fragment fragment = getFragmentManager().findFragmentById(R.id.mft);

        // 取得 Fragment 中的 Button2
        button = (Button) fragment.getView().findViewById(R.id.btn2);

        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                activityTextView.setText("我被 activity 點擊了...");
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

執行專案即可看到效果:Fragment 內的按鈕控制 Fragment 自己的文字,Activity 內取得的按鈕則控制 Activity 的文字。

六、一個關鍵問題:Fragment 能操作 Activity 的元件嗎?

衍生出的問題是:Fragment 能不能與 Activity 通訊?答案是能,但方式有講究。

直覺上會想用:

getActivity().findViewById(R.id.atxv);

但實測這行會回傳 null,取不到 Activity 中的 View 元素。所以 Button2 的操作只能寫在 Activity 裡。

為什麼會這樣?有兩個層次的原因。

技術層面:Fragment 的 onCreateView() 執行時,Activity 的 setContentView() 已經跑完,atxv 理應存在。回傳 null 通常是時序問題——若這行被放在 Fragment 初始化階段執行,Activity 的版面尚未就緒。此外 R.id.atxv 這個 ID 必須確實存在於當前的版面樹中。

設計層面:更重要的一點是,Fragment 直接伸手去拿 Activity 的 View,本身就是不好的設計。這會讓 Fragment 與特定 Activity 的版面緊密耦合,重用性蕩然無存。正確做法是把溝通抽象成介面:

public class MainFragment extends Fragment {

    /** Activity 要實作這個介面 */
    public interface OnFragmentInteractionListener {
        void onBtn2Clicked();
    }

    private OnFragmentInteractionListener mListener;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " 必須實作 OnFragmentInteractionListener");
        }
    }

    // 在 Fragment 內觸發,交由 Activity 決定要做什麼
    private void notifyActivity() {
        if (mListener != null) {
            mListener.onBtn2Clicked();
        }
    }
}

反過來,Activity 要操作 Fragment 時,則透過 Fragment 自己開放的公開方法,或直接呼叫 FragmentTransaction 的 API。

一句話總結:Fragment 之間、Fragment 與 Activity 之間的溝通,應該走「介面回呼」而非「直接抓對方的 View」。這個原則在後續使用 ViewModel 或 LiveData 的架構中會變得更清楚——資料狀態放在共用元件裡,雙方各自訂閱變化,耦合度降到最低。

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