【问题标题】:notifyDataSetChanged() on my adapter does not update the listview, why?我的适配器上的 notifyDataSetChanged() 没有更新列表视图,为什么?
【发布时间】:2011-12-16 17:00:32
【问题描述】:

我有一个扩展 listactivity 的活动,在这个类中扩展我有一个扩展 baseadapter 的类。

现在在我的列表活动中我有这个 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 ??

如果我有该行,则视图不会自行更新,但如果我使用 setListAdapter 下的行,则一切正常。

【问题讨论】:

  • 最好将代码显示您如何使用 notifyDataSetChanged() 更新列表。

标签: android listview listactivity notify baseadapter


【解决方案1】:

如果适配器已经设置,再次设置它不会刷新列表视图。而是先检查列表视图是否有适配器,然后调用相应的方法。

我认为在设置列表视图时创建适配器的新实例并不是一个好主意。相反,创建一个对象。

BuildingAdapter adapter = new BuildingAdapter(context);

    if(getListView().getAdapter() == null){ //Adapter not set yet.
     setListAdapter(adapter);
    }
    else{ //Already has an adapter
    adapter.notifyDataSetChanged();
    }

【讨论】:

    【解决方案2】:

    您是否尝试过为此使用 AsyncTaskLoader 而不是 AsyncTask。 Loaders 正是为这种东西而设计的。请注意,即使 Loaders 在 API-10 之前不可用,您仍然可以通过 API-4 及更高版本的 android Support Pacakge 轻松访问它们。

    【讨论】:

      【解决方案3】:

      您可以更新 UI 的唯一位置是 onProgressUpdate(...);。从您的doInBackground(...) 拨打publishProgress(...)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多