Android學習路線(二十三)運用Fragment構建動態UI——Fragment間通訊

爲了要重用Fragment的UI組件,你應該爲它們每一個都構建一個完整獨立的,模塊化的組件來定義他自身的佈局和行爲。一旦你定義了這些可重用的Fragments,你可以通過activity關聯它們同時通過應用邏輯連接它們來實現所有複雜的UI。

你通常都希望一個fragment能夠和其他的fragment進行交互,例如基於用戶的操作改變內容。所有的fragment之間的交流的完成都通過activity的關聯。兩個fragment之間一定不要直接交流。

定義一個接口


要允許一個fragment和它的activity通訊,你可以在fragment類中定義一個接口,然後再activity中實現它。Fragment在onAttach()方法中獲取這個接口的實現,這樣之後就能夠調用這些接口來達到和activity通訊的目的。

下面是一個fragment和activity通訊的例子:

public class HeadlinesFragment extends ListFragment {
    OnHeadlineSelectedListener mCallback;

    // Container Activity must implement this interface
    public interface OnHeadlineSelectedListener {
        public void onArticleSelected(int position);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        
        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            mCallback = (OnHeadlineSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener");
        }
    }
    
    ...
}

現在這個fragment可以通過使用onHeadlineSelectedListener接口的實例mCallback來調用onArticleSelected() 方法(或者這個接口中的其它方法)來向activity傳遞消息了。

例如,當用戶點擊fragment中列表的item時,下面的方法將會被調用。這個fragment會使用這個回調接口來將事件傳遞給它的父activity。

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        // Send the event to the host activity
        mCallback.onArticleSelected(position);
    }

實現這個接口


爲了接收fragment的回調事件,包含這個fragment的activity就必須實現定義在fragment的接口。

例如,下面的這個activity就實現了上面例子中的接口:

public static class MainActivity extends Activity
        implements HeadlinesFragment.OnHeadlineSelectedListener{
    ...
    
    public void onArticleSelected(int position) {
        // The user selected the headline of an article from the HeadlinesFragment
        // Do something here to display that article
    }
}

向Fragment傳遞消息


宿主activity可以通過使用findFragmentById()獲取的fragment實例來向fragment傳遞消息,然後直接調用這些fragment的public方法。 

例如,設想上面的那個activity包含另一個fragment,這個fragment是用來展示通過前面的回調方法返回的數據指定的item。在這個案例中,這個activity可以這個activity可以將接收的這些信息傳遞給其它的fragment用來顯示這個item:

public static class MainActivity extends Activity
        implements HeadlinesFragment.OnHeadlineSelectedListener{
    ...

    public void onArticleSelected(int position) {
        // The user selected the headline of an article from the HeadlinesFragment
        // Do something here to display that article

        ArticleFragment articleFrag = (ArticleFragment)
                getSupportFragmentManager().findFragmentById(R.id.article_fragment);

        if (articleFrag != null) {
            // If article frag is available, we're in two-pane layout...

            // Call a method in the ArticleFragment to update its content
            articleFrag.updateArticleView(position);
        } else {
            // Otherwise, we're in the one-pane layout and must swap frags...

            // Create fragment and give it an argument for the selected article
            ArticleFragment newFragment = new ArticleFragment();
            Bundle args = new Bundle();
            args.putInt(ArticleFragment.ARG_POSITION, position);
            newFragment.setArguments(args);
        
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

            // Replace whatever is in the fragment_container view with this fragment,
            // and add the transaction to the back stack so the user can navigate back
            transaction.replace(R.id.fragment_container, newFragment);
            transaction.addToBackStack(null);

            // Commit the transaction
            transaction.commit();
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章