【问题标题】:How can I refresh my ListView using BaseAdapter如何使用 BaseAdapter 刷新我的 ListView
【发布时间】:2016-04-18 18:12:23
【问题描述】:

我尝试使用 notifyDataSetChanged() 刷新我的列表视图,但这标记为红色。我使用 ListView 之类的扩展适配器,因此 notifyDataSetChaned 它应该可以工作,但不然。

下面是我的声明ListView和ArrayList。

ListView listview;
ArrayList<ListData> myList = new ArrayList<>();

我是这样设置我的列表的:

listview = (ListView) findViewById(R.id.listView);
listview.setAdapter(new MyBaseAdapter(this, myList));

我也使用 setOnScrollListener,我希望我的列表视图在 SROLL_STATE = 0 时刷新;

    listview.setOnScrollListener(new AbsListView.OnScrollListener() {

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            int position = listview.getFirstVisiblePosition();

            SCROLL_STATE = position;

            if (SCROLL_STATE == 0) {
                listview.notifyDataSetChanged();  // Here is a problem, because it's not work
            }

        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

        }
    });

【问题讨论】:

  • 也许你应该检查你导入的包名是你的扩展列表视图。

标签: java android listview arraylist notifydatasetchanged


【解决方案1】:

notifyDataSetChanged()BaseAdapter 类的方法,不是 ListView 类的方法。因此,调用listView.notifyDatasSetChanged();在逻辑和语法上都是不正确的。

将此行替换为

listView.getAdapter().notifyDataSetChanged();

一切顺利:)

【讨论】:

  • 我的 BaseAdapter 是 public class MyBaseAdapter "public class MyBaseAdapter extends BaseAdapter {" 我尝试从其他活动调用 notifyDataSetChanged()。不幸的是,您的示例无法解决我的问题。
  • 我明白了。 notifyDataSetChanged() 是该类的公共方法。我建议的行是首先获取与 listView 关联的适配器,然后调用 notifyDataSetChanged() 方法以在底层数据发生任何更改(数据中的任何插入或删除)时重绘 listview。
  • 我不能用这个方法。我会解释发生了什么。该包是从公共 JSONArray 创建的。在这个数组中更多的是一个 JSONObject,它工作得很好。在后台使用 IntentService 和 HttpRequest 会下载新数据(如果存在)。下载新数据时,全局 JSONAarray 会更改,但我的列表视图不会。现在我必须在不创建新活动的情况下刷新列表视图。
  • 我不确定为什么会出现问题。无论如何,也许这会有所帮助:androidadapternotifiydatasetchanged.blogspot.in/2013/02/…
  • SeaDog - 我不明白您的解释如何改变了 Narayan Acharya 答案的相关性。 ListView 根本不提供方法“notifyDataSetChanged”...但 getAdapter() 提供。
【解决方案2】:

定义一个适配器对象, MyBaseAdapter 适配器=新 MyBaseAdapter(this, myList); 适配器.notifyDataSetChanged();

【讨论】:

  • 我有一个日志:在没有当前上下文的情况下调用 OpenGL ES API(每个线程记录一次)
  • 太棒了!我有这个日志是因为我创建了一个堆栈活动并且某处是错误的。当我打开一项活动并使用您的解决方案时,一切都是最好的。请告诉我如何从 IntentService 刷新列表视图?我创建了公共静态 MyBaseAdapter mListAdapter 并尝试从 IntentService 调用该方法,但我的应用程序已关闭。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-25
  • 1970-01-01
  • 2013-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-23
相关资源
最近更新 更多