Fragment笔记

来源:互联网 发布:微信sdk数据统计接入 编辑:程序博客网 时间:2024/05/06 18:26
  • All Fragment-to-Fragment communication is done through the associated Activity
  • 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.
    Demo:
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");        }    }    ...}

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

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

test

0 0
原创粉丝点击