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

Android 學習路線(二十三):Fragment 之間的通訊

編輯:關於 Android 程式設計

先把位置佔著,翻譯待補。以下暫留原文。

In order to reuse the Fragment UI components, you should build each as a completely self-contained, modular component that defines its own layout and behavior. Once you have defined these reusable Fragments, you can associate them with an Activity and connect them with the application logic to realize the overall composite UI.

Often you will want one Fragment to communicate with another, for example to change the content based on a user event. All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.

Define an Interface

To allow a Fragment to communicate up to its Activity, you can define an interface in the Fragment class and implement it within the Activity. The Fragment captures the interface implementation during its onAttach() lifecycle method and can then call the Interface methods in order to communicate with the Activity.

Here is an example of Fragment to Activity communication:

public class HeadlinesFragment extends ListFragment {

    OnHeadlineSelectedListener mCallback;

    // 容器 Activity 必須實作這個介面
    public interface OnHeadlineSelectedListener {
        public void onArticleSelected(int position);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        // 確認容器 Activity 確實實作了回呼介面,否則直接拋出例外
        try {
            mCallback = (OnHeadlineSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener");
        }
    }
    // ...
}

Now the fragment can deliver messages to the activity by calling the onArticleSelected() method (or other methods in the interface) using the mCallback instance of the OnHeadlineSelectedListener interface.

For example, the following method in the fragment is called when the user clicks on a list item. The fragment uses the callback interface to deliver the event to the parent activity.

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    // 把事件交給宿主 Activity
    mCallback.onArticleSelected(position);
}

Implement the Interface

In order to receive event callbacks from the fragment, the activity that hosts it must implement the interface defined in the fragment class.

For example, the following activity implements the interface from the above example.

public static class MainActivity extends Activity
        implements HeadlinesFragment.OnHeadlineSelectedListener {

    public void onArticleSelected(int position) {
        // 使用者從 HeadlinesFragment 選了一則標題,在這裡決定如何呈現內容
    }
}

Deliver a Message to a Fragment

The host activity can deliver messages to a fragment by capturing the Fragment instance with findFragmentById(), then directly call the fragment's public methods.

For instance, imagine that the activity shown above may contain another fragment that's used to display the item specified by the data returned in the above callback method. In this case, the activity can pass the information received in the callback method to the other fragment that will display the item:

public static class MainActivity extends Activity
        implements HeadlinesFragment.OnHeadlineSelectedListener {

    public void onArticleSelected(int position) {
        ArticleFragment articleFrag = (ArticleFragment)
                getSupportFragmentManager().findFragmentById(R.id.article_fragment);

        if (articleFrag != null) {
            // 找到目標 Fragment,代表目前處於雙欄版面
            // 直接呼叫它的公開方法更新內容
            articleFrag.updateArticleView(position);
        } else {
            // 否則是單欄版面,必須替換 Fragment
            ArticleFragment newFragment = new ArticleFragment();
            Bundle args = new Bundle();
            args.putInt(ArticleFragment.ARG_POSITION, position);
            newFragment.setArguments(args);

            FragmentTransaction transaction =
                    getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.fragment_container, newFragment);
            transaction.addToBackStack(null);
            transaction.commit();
        }
    }
}

重點整理

這段程式示範的其實是一個很值得記住的設計原則:Fragment 之間永遠不直接溝通,一律透過宿主 Activity 居中轉傳。

為什麼要這樣設計?因為 Fragment 的存在前提是「可重用」。一旦兩個 Fragment 直接互相引用,它們就被綁死了,無法被拆到別的 Activity 使用,也無法自由調整版面配置。透過 Activity 轉一手,Fragment 才能維持獨立。

實作上有兩個方向:

Fragment → Activity:在 Fragment 中定義介面,於 onAttach() 時取得實作並做型別檢查(檢查失敗就拋例外,讓問題在開發階段就暴露,而非上線後靜默失效)。

Activity → Fragment:用 findFragmentById() 抓到實例後直接呼叫其公開方法。若抓不到,通常代表目前是單欄版面,改走 Fragment 替換流程。

最後那個 if-else 判斷尤其實用——同一份程式碼能同時適配手機的單欄與平板的雙欄,這正是 Fragment 設計的核心價值所在。

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