我正在尝试使用 notifyDatasetChanged() 从位置侦听器的 onLocationChanged 函数中更新我的 Activity 的 ListView,但它不起作用。但是,我可以在代码中的同一点使用 setListAdapter,这将起作用。
这是我的代码:
public class TestListeners extends ListActivity {
ArrayAdapter adapter;
private final LocationListener networkLocationListener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
switch (status) {
case LocationProvider.AVAILABLE:
break;
case LocationProvider.OUT_OF_SERVICE:
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
break;
}
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onLocationChanged(Location location) {
checkProximity(location.getLatitude(), location.getLongitude(), cx);
}
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//get a list here venueNamesArray
//etc
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1,
venueNamesArray);
setListAdapter(adapter);
}
private void checkProximity(double curLat, double curLon, Context cx) {
//get a different list here venueNamesArray
//etc
adapter = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_list_item_1, android.R.id.text1,
venueNamesArray);
adapter.notifyDataSetChanged();//this doesnt work and no error is thrown
setListAdapter(adapter);//this works
}
}
我想使用 notifyDatasetChanged() 而不是 setListAdapter 的原因是因为 listview 在设置时会滚动回顶部。当我使用 notifyDatasetChanged() 时没有抛出错误,所以我很难明白为什么这不起作用。
我已经尝试为此使用普通的 ListView 而不是扩展 ListActivity 并遇到了同样的问题。