Android Fragment与Activity通过回调实现通信
1.首先在Fragment中声明一个监听器接口
import android.app.Activity;
public class BlackListFragment extends ListFragment implements View.OnClickListener{
...
OnArticleSelectedListener mListener;
/**
* 传递事件:
*
* 1.定义接口
*
* 2.在onAttach方法中检测Activity或其他Fragment是否已经实现接口
*
* 3.在Fragment的某个地方调用接口实例,如监听中调用,通过实例调用接口中的方法
*
* 4.在Activity中实现接口,实现接口的方法即可
*
*
*/
// Container Activity must implement this interface
public interface OnArticleSelectedListener {
public void onArticleSelected();
public String getContent();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnArticleSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnArticleSelectedListener");
}
}
//触发该监听器的地方:
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
// super.onListItemClick(l, v, position, id);
Cursor c = (Cursor) mAdapter.getItem(position);
black_phone = c.getString(2);
if (mListener!=null) {mListener.onArticleSelected();
String name = mListener.getContent();
showToast(name);}
}
}
2.在Activity中实现该接口
public class MainActivity extends FragmentActivity implements
BlackListFragment.OnArticleSelectedListener {
@Override
public void onArticleSelected() {
showToast("显示问题实现");
mButton.setOnClickListener(this);
}
@Override
public String getContent() {
return "实现接口方法返回字符串";
}
}
3.案例说明
当在BlackListFragment 中触发mListener.onArticleSelected(); 方法时,系统自动回调MainActivity 中的 onArticleSelected() 方法,相当于Fragment把事件传递给Activity了,由Activity来监听Fragment触发的动作。