您的位置:首页 > 移动开发 > Android开发

Android Fragment---给Activity创建事件回调

2012-04-26 01:12 459 查看
在某些案例中,可能需要Fragment与Activity共享事件。在Fragment内部定义一个回调接口是一个好方法,并且规定由持有它的Activity实现这个回调方法。当Activity通过接口接受回调时,它能在必要时与布局中的其他Fragment共享信息。

例如,如果一个新闻类的应用程序在一个Activity中有两个Fragment---一个用来显示文章列表(Fragment A),另一个用来显示文章内容(Fragment B)---然后再列表项目被选中时Fragment A必须告诉Activity,以便它能告诉Fragment B显示对应的文章。在下面的例子中在Fragment A的内部声明了OnArticleSelectedListener接口。

public static class FragmentA extends ListFragment {
...
// Container Activity must implement this interface
public interface OnArticleSelectedListener {
public void onArticleSelected(Uri articleUri);
}
...
}


然后,持有这个Fragment的Activity要实现OnArticleSelectedListener接口,并且要重写onArticleSelected()方法把来自Fragment A的事件通知给Fragment B。要确保持有Fragment的Activity实现这个接口, Fragment A 的onAttach()回调方法(当Fragment被添加到Activity时系统调用这个方法)通过类型转换onAttach()传入的Activity来实例化一个OnArticleSelectedListener的实例。

public static class FragmentA extends ListFragment {
OnArticleSelectedListener mListener;
...
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnArticleSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnArticleSelectedListener");
}
}
...
}


如果这个Activity没有实现这个接口,那么Fragment会抛出ClassCastException异常。如果成功,那么mListener成员就会拥有Activity实现的OnArticleSelectedListener对象的引用,以便Fragment A能够通过OnArticleSelectedListener接口定义的回调方法和Activity共享事件。例如,如果ListFragment继承了Fragment A,那么用户每次点击列表项时,系统都会调用Fragment中的onListItemClick()方法,然后调用onArticleSelected()方法和Activity共享事件:

public static class FragmentA extends ListFragment {
OnArticleSelectedListener mListener;
...
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Append the clicked item's row ID with the content provider Uri
Uri noteUri = ContentUris.withAppendedId(ArticleColumns.CONTENT_URI, id);
// Send the event and Uri to the host activity
mListener.onArticleSelected(noteUri);
}
...
}


传递给onListItemClick()的id参数是被点击项目的行ID,Activity(或其他的Fragment)使用这个ID从应用程序的ContentProvider对象中获取对应的文章。

关于使用有效内容提供器的更多内容,请看内容提供器(Content Providers)文档。

注:本人转载系个人觉得翻译的很好,值得收藏,且自己回头看着方便。

如有兴趣请访问作者官方博客http://blog.csdn.net/FireOfStar
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐