恕我直言,“最干净”的方式是通过接口和注册侦听器
创建两个接口:
public interface LocationListener{
public void onLocationAvailable(/* whatever data you want to pass */ );
}
public interface LocationListenersRegistry{
public void addLocationListener(LocationListener listener);
public void removeLocationListener(LocationListener listener);
}
然后你让你的活动实现LocationListenersRegistry
和你的片段实现LocationListener
在您的活动中private ArrayList<LocationListener>
,您将根据添加/删除方法添加和删除侦听器。每次您的活动接收到新数据时,它都应该对其进行处理,然后将其传递给数组上的所有侦听器。
在您应该从活动中注册和注销自己的片段上onPause
,onResume
如下所示:
onResume(){
super.onResume();
((LocationListenersRegistry)getActivity()).addLocationListener(this);
}
onPause(){
super.onPause();
((LocationListenersRegistry)getActivity()).removeLocationListener(this);
}
编辑:
您的活动实现了 LocationListenersRegistry,然后将具有以下代码:
public class MyActivity extends Activity implements LocationListenersRegistry {
private ArrayList<LocationListener> listeners = new ArrayList<LocationListener>();
public void addLocationListener(LocationListener listener){
listeners.add(listener);
}
public void removeLocationListener(LocationListener listener){
listeners.remove(listener);
}
然后每当用户单击菜单按钮时:
for(LocationListener l:listeners)
l.onLocationAvailable(/* pass here the data for the fragment */);
并且您的片段将实现 LocationListener
public class MyFragment extends Fragments implements LocationListener{
public void onLocationAvailable( /* receive here the data */){
// do stuff with your data
}