我有一个扩展 listactivity 的 Activity ,在这个类中扩展我有一个扩展 baseadapter 的类。
现在在我的列表 Activity 中我有这个 onCreate
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new BuildingAdapter(this));
final ProgressDialog loading = new ProgressDialog(this);
loading.setProgressStyle(ProgressDialog.STYLE_SPINNER);
loading.setTitle("Laddar");
loading.setMessage("Hämtar data från servern");
loading.show();
new AsyncTask<Void, Void, DataPacket.Data>()
{
@Override
protected DataPacket.Data doInBackground(Void... params){
return ServerConnection.getBuildings();
}
@Override
protected void onPostExecute(DataPacket.Data param) {
((MainenanceApplication)getApplication()).setDataStructure(param);
loading.dismiss();
//((BuildingAdapter)getListAdapter()).notifyDataSetChanged();
setListAdapter(new BuildingAdapter(BuildingSelectionActivity.this));
}
}.execute();
}
这按预期工作,但我的问题是在 onPostExecute 中更新列表适配器使用的数据结构。 为什么我不能直接调用 notifyDataSetChanged ??
如果我有那一行, View 不会自行更新,但如果我在我执行 setListAdapter 的地方使用那一行,它一切正常。
最佳答案
如果adapter已经设置好,再次设置不会刷新listview。相反,首先检查 ListView 是否有适配器,然后调用适当的方法。
我认为在设置 ListView 时创建适配器的新实例不是一个好主意。相反,创建一个对象。
BuildingAdapter adapter = new BuildingAdapter(context);
if(getListView().getAdapter() == null){ //Adapter not set yet.
setListAdapter(adapter);
}
else{ //Already has an adapter
adapter.notifyDataSetChanged();
}
关于android - 我的适配器上的 notifyDataSetChanged() 没有更新 ListView ,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7919691/