【问题标题】:Android: How to update ListView when user Scrolls down to bottom using eventBus and arrayadapterAndroid:当用户使用 eventBus 和 arrayadapter 向下滚动到底部时如何更新 ListView
【发布时间】:2015-03-12 23:18:53
【问题描述】:

最初的 listView 有 20 个项目。当用户向下滚动到底部时,我需要用接下来的 20 个项目更新 listView。我正在使用 ArrayAdapter 来实现这一点。 listView 中的项目来自 REST API,该 API 使用 EventBus(而不是 AsyncTask)将 startIndex 和限制作为参数。

    public void onEventMainThread(MessageListEvent event) {
    //Create Adapter
    //Set Adapter to List View
    customListAdapter = new CustomListAdapter(getActivity(), event.itemList);

    Log.d("Scroll","Inside OnEventMainThread");
    mListView = (ListView) view.findViewById(android.R.id.list);

    mListView.setAdapter(customListAdapter);
    mListView.setOnItemClickListener(this);

    // This loads the next 20 images when scrolled all the way down to bottom.
    // Overrides onScroll and onScrollStateChanged function
    mListView.setOnScrollListener(this);
}

@Override
public void onScroll(AbsListView view, int firstVisibleItem,
                     int visibleItemCount, int totalItemCount) {
    int loaded = firstVisibleItem+visibleItemCount;
    if(loaded>=totalItemCount && startIndex+19==loaded) {
        startIndex = loaded+1; //Static variable used in onEventBackgroundThread(...). Download starts from this item
        EventBus.getDefault().post(new StartDownloadEvent()); // This will download the next 20 and update the list to 40 items but position starts from 0 again. onEventBackgroundThread(...) downloads the data and updates the list.
    }
}

我在 stackOverflow 中发现了类似的问题,但都在使用 AsyncTask。我不想使用 AsyncTask 并想使用 EventBus 来实现。

【问题讨论】:

    标签: android android-listview android-arrayadapter greenrobot-eventbus


    【解决方案1】:

    AsyncTaskEventBus 是两个完全不同的东西。 AsyncTask 用于在主线程之外做一些事情,这些事情可能需要很长时间(比如网络的事情),如果不在另一个线程上做会阻塞主线程。 EventBus 只是应用程序各部分(活动、片段等)之间的一种通信方式。

    虽然您确定可以使用 EventBus 通知某些类需要为您的列表加载更多项目,并且您也可以使用它来通知您的 ListView/ 适配器已加载新项目,但它不会这样做任何网络内容,例如为您加载新项目。 您要么必须自己执行此操作(在主线程之外,例如 AsyncTask),要么使用诸如 this 之类的库。

    当你在做
    EventBus.getDefault().post(new StartDownloadEvent()); 除非您有一个接收事件并执行 api 调用的类,否则什么都不会发生。

    【讨论】:

    • 我是 Android 新手,这有助于我更好地理解。正如你所说,我可以用新列表通知适配器。即新列表包含现有的 20 项和新的 20 项,共 40 项。但是当我向下滚动到第 20 项时,我失去了位置。列表从 0 开始重新加载 40 个项目。
    • 您显然在接收到您不需要的新项目(在 MessageListEvent 上)时创建了一个新适配器,只需调用 adapter.notifyDataSetChanged。如果不是这种情况,您可能需要提出一个新问题并发布您更新的代码。
    • 我将接下来的 20 个项目添加到适配器并调用 notifyDataSetChanged,如下所示。 ` getActivity().runOnUiThread(new Runnable() { @Override public void run() { customListAdapter.addAll(newItemList); customListAdapter.notifyDataSetChanged(); } });` 它仍然无法正常工作。我试过mListView.setSelection(startIndex);,但没用。但是当我在 runOnUIThread 函数之外编写上述代码并在加载 40 个项目后失败时工作。
    猜你喜欢
    • 1970-01-01
    • 2019-06-27
    • 1970-01-01
    • 2018-02-27
    • 2021-08-22
    • 2012-05-17
    • 2021-05-29
    • 1970-01-01
    • 2011-11-28
    相关资源
    最近更新 更多