码迷,mamicode.com
首页 > 移动开发 > 详细

android

时间:2015-03-11 17:03:13      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:

然后这里说的是fragment与activityt的交互,一般的做法是在Fragment中定义一个接口。然后activity去实现这个接口。然后framment在onAttach()这中去捕获接口的实现,大概就是这么个过程。

原话是:

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.

然后training给的example:

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");
        }
    }

    ...
}

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

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
}
}

如果activity要传递消息给fragment就太简单了,直接调用fragment的方法。

android

标签:

原文地址:http://www.cnblogs.com/CoolRandy/p/4329977.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!