onAttach回调从片段活动 [英] onAttach callback from fragment to activity
问题描述
我想从片段
发送字符串
数据活动
。
我已经阅读了文章关于Android开发的片段和活动之间的通信,使用 onAttach
回调。
I have read the article about communicating between fragment and activity in android developer, using onAttach
callback.
谁能解释清楚如何从片段数据发送到活动?
can anyone explain clearly how to send data from fragment to activity?
推荐答案
您应该做这样的事情。首先创建一个将使用的comunicate与你的活动,例如接口:
You should do something like this. First create an interface which will use to comunicate with your activity for example :
public interface OnViewSelected {
public void onViewSelected(int viewId);
}
和您的 onAttach
做到这一点:
OnViewSelected _mClickListener;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
_mClickListener = (OnViewSelected) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement onViewSelected");
}
}
在你的片段执行 OnClickListener
并在的onClick()
办法做到这一点:
In your Fragment implement OnClickListener
and in your onClick()
method do this :
@Override
public void onClick(View v) {
_mClickListener.onViewSelected(456);
}
在,在你的活动中,你必须实现你在片段中创建的接口,它会问你要添加未实现的方法,并在你的活动,你将有这样的功能:
After that in your Activity you have to implement the interface you created in your Fragment and it will ask you to add unimplemented methods and in your activity you will have function like this :
@Override
public void onViewSelected(int data) {
Log.d("","data : "+data); // this value will be 456.
}
这就是全部。 :)
That's all. : )
这篇关于onAttach回调从片段活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!