【问题标题】:Refresh ListView when an AsyncTask is inside the Adapter当 AsyncTask 在适配器内时刷新 ListView
【发布时间】:2016-01-09 22:14:46
【问题描述】:

我有一个 ListView 和一个自定义适配器。自定义适配器实现了一个 AsyncTask 来从服务器加载一些图像。创建活动时一切正常。但是,ListView 有一个加载按钮来加载更多行,每行包含一个图像。按下加载按钮时,新数据(图像)会正确添加到 ListView。但是,尽管调用了 notifyDataSetChanged,但 ListView 并未刷新。我必须移动 scoll 以刷新 ListView 并显示新数据。问题是新图像是在 Adapter 内的 AsyncTask 中加载的,当在 MainActivity 中调用 notifyDataSetChanged 时,AsyncTask 尚未完成。所以,我的问题是:有没有办法在 AsyncTask 完成后刷新 ListView?在 Adapter 内部调用 notifyDataSetChanged 还是其他替代方法?

【问题讨论】:

  • 为您的activity 实现一个interface 并从您的onPostExecute() 方法更新它。

标签: android listview android-listview android-asynctask


【解决方案1】:

在您的 asynctask onPostExecute 中应该是这样的:

@Override
  protected void onPostExecute(String result) {
   ((MainActivity) getActivity).notifyDataChanged();
  }

根据您的代码的组织方式,您将调用notifyDataChanged(),方式与此类似。

【讨论】:

  • 问题是notifyDataSetChanged是Adapter要使用的方法。
  • 没关系,调用MyListAdapter.this.notifyDataSetChanged();,其中MyListAdapter 是您的自定义适配器的类的名称。
【解决方案2】:

所以,我的问题是:有没有办法在 AsyncTask 完成后刷新 ListView?

是的,你可以这样做:

  1. ListView 传递给 AsyncTask
  2. 覆盖onPostExecute() 方法,
  3. onPostExecute()方法中调用notifyDataChanged

【讨论】:

  • 问题是 notifyDataSetChanged 是从适配器使用的方法,我不能将适配器传递给它自己。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-15
相关资源
最近更新 更多