使用自定义事件侦听器java
我试图设置一个自定义事件监听器,从我的MainActivity到另一个singleton类,但我似乎不知道我做错了什么。我在mainactivity中设置了一个映射片段,当调用onLocationChanged()时,我希望我的DB类侦听这个新位置以将其添加到数据库中。这就是我目前所拥有的。我只展示与接口和侦听器相关的代码: MainActivity.java使用自定义事件侦听器java,java,android,Java,Android,我试图设置一个自定义事件监听器,从我的MainActivity到另一个singleton类,但我似乎不知道我做错了什么。我在mainactivity中设置了一个映射片段,当调用onLocationChanged()时,我希望我的DB类侦听这个新位置以将其添加到数据库中。这就是我目前所拥有的。我只展示与接口和侦听器相关的代码: MainActivity.java public List<OnNewLocationRaisedListener> locationListeners; p
public List<OnNewLocationRaisedListener> locationListeners;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
locationListeners = new ArrayList<OnNewLocationRaisedListener>();
...
}
@Override
public void onLocationChanged(Location location) {
WeatherDBAccess._context = this;
m_CurrentLocation = location;
WeatherEvent event = new WeatherEvent();
if (record) {
LatLng currLatLng = new LatLng(m_CurrentLocation.getLatitude(), m_CurrentLocation.getLongitude());
for(OnNewLocationRaisedListener listener: locationListeners){
listener.OnNewLocationRaised(event,currLatLng);
}
}
}
public interface OnNewLocationRaisedListener {
void OnNewLocationRaised(WeatherEvent event, LatLng latlon);
}
我可以不从活动中执行此操作吗?
main活动。locationListeners
是实例成员,不能像您当前在WeatherDbAccess中尝试的那样静态访问
既然WeatherDBAccess
是一个单例,那么您应该做的是从MainActivity
中注册并注销它作为locationListener
。它应该与注册和注销LocationListener
的生命周期回调方法相同
由于您没有显示代码,让我们假设它位于onResume()
和onPause()
中,但是您可以将add和remove方法放在它们真正属于的任何位置
@Override
public void onResume() {
super.onResume();
locationListeners.add(WeatherDBAccess.Instance());
}
@Override
public void onPause() {
super.onPause();
locationListeners.remove(WeatherDBAccess.Instance());
}
@Override
public void onResume() {
super.onResume();
locationListeners.add(WeatherDBAccess.Instance());
}
@Override
public void onPause() {
super.onPause();
locationListeners.remove(WeatherDBAccess.Instance());
}