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

Android 資料傳遞筆記(三):用介面回呼把 Activity 的資料送進 Fragment

編輯:關於 Android 程式設計

Activity 與 Fragment 之間要交換資料,做法其實不少,但最常見、也最能體現解耦思想的一種,就是「介面回呼」(Interface Callback)。本文用一個可運行的完整範例,把這個模式拆開講清楚。

一、先理清思路

很多人第一次聽到「回呼」會覺得很玄,本質上它只是把「誰來接收資料」這件事,交給執行期才決定。整個流程可以濃縮成三步:

  1. 在資料的發出方(這裡是 Activity)內部宣告一個介面,介面裡定義一個方法,方法參數的型別就是你要傳出去的資料型別。
  2. 在發出方再提供一個公開方法,用來接收「介面實例」並保存起來。
  3. 接收方(Fragment)拿到發出方的參照後,把符合介面的實作物件交給它。

兩種常見寫法:

  • 方式一:讓 Fragment 直接 implements 這個介面,然後呼叫 setData(this),把自身傳進去。
  • 方式二:Fragment 不實作介面,而是在呼叫時傳入一個匿名內部類 new DataChange() { ... },實作那個尚未完成的方法。

抽象描述容易暈,直接看程式碼反而清楚。

二、版面安排

先用一個 FrameLayout 當作 Fragment 的容器,底部放兩個 Button 負責切換:

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

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp">

        <Button
            android:id="@+id/button1"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:onClick="button"
            android:text="FragmentA" />

        <Button
            android:id="@+id/button2"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:onClick="button"
            android:text="FragmentB" />
    </LinearLayout>
</LinearLayout>

三、在 Activity 中定義回呼介面

介面裡的那個方法,參數就是準備外傳的資料:

public interface DataChange {
    void setDataChange(String qqq);
}

接著宣告介面物件,並提供公開方法讓外部注入實作:

static DataChange dataChange;

public void setData(DataChange dataChange) {
    this.dataChange = dataChange;
}

四、取得資料並回呼

本範例在 Activity 中發請求,再把結果丟回 Fragment。網路部分選用了 xUtils 這個第三方套件:

private void getData(String path) {
    HttpUtils utils = new HttpUtils();
    utils.send(HttpRequest.HttpMethod.GET, path, new RequestCallBack<String>() {
        @Override
        public void onSuccess(ResponseInfo<String> responseInfo) {
            String result = responseInfo.result;
            // 透過介面把資料推送出去
            if (dataChange != null) {
                dataChange.setDataChange(result);
            }
        }

        @Override
        public void onFailure(HttpException e, String s) {
            Toast.makeText(MainActivity.this, "請求資料失敗" + s, Toast.LENGTH_SHORT).show();
        }
    });
}

切換 Fragment 的動作則交給 FragmentManager 完成:

private void changeFragment(Fragment fragment) {
    getSupportFragmentManager()
        .beginTransaction()
        .replace(R.id.main_frameLayout, fragment)
        .commit();
}

點擊事件依按鈕決定要顯示哪個 Fragment、要請求哪個網址:

public void button(View view) {
    switch (view.getId()) {
        case R.id.button1:
            changeFragment(fragmentA);
            getData("https://mobile.ximalaya.com/mobile/v1/album?albumId=2839012");
            break;
        case R.id.button2:
            changeFragment(fragmentB);
            getData("https://mobile.ximalaya.com/mobile/v1/album?albumId=2839015");
            break;
    }
}

五、兩個 Fragment 的兩種接法

兩個 Fragment 的版面幾乎一樣,都是一個 TextView 用來呈現收到的資料:

<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:id="@+id/fragmemt_b_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

FragmentA:匿名內部類寫法

View view = inflater.inflate(R.layout.fragment_a, null);
textView = (TextView) view.findViewById(R.id.fragmemt_a_textview);

MainActivity activity = new MainActivity();
activity.setData(new MainActivity.DataChange() {
    @Override
    public void setDataChange(String aaa) {
        textView.setText(aaa);
    }
});

FragmentB:實作介面寫法

public class FragmentB extends Fragment implements MainActivity.DataChange {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_b, null);
        textView = (TextView) view.findViewById(R.id.fragmemt_b_textview);
        // 把 this 交給 Activity
        ((MainActivity) getActivity()).setData(this);
        return view;
    }

    @Override
    public void setDataChange(String qqq) {
        textView.setText(qqq);
    }
}

六、幾個實務上的提醒

原始範例在 FragmentA 裡用 new MainActivity() 取得物件,這種寫法其實是有問題的:Activity 必須由系統建立,手動 new 出來的實例沒有任何生命週期意義,也不會是畫面上那一個。實務上應該改用 ((MainActivity) getActivity()).setData(...),也就是 FragmentB 的寫法。

另外,把介面物件存成 static 容易造成記憶體洩漏。比較穩妥的做法是在 Fragment 的 onAttach 註冊、onDetach 取消註冊,避免 Activity 被銷毀後仍被 hold 住。

執行結果如下:

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