0

最初,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 来实现。

4

1 回答 1

0

AsyncTask and EventBus are two totally different things. AsyncTask is used to do stuff off the main thread, things that might take a long time (like network stuff) and would block the main thread if not done on another thread. EventBus is just a means of communication between the parts of your app (Activities, Fragments etc).

While you sure can use EventBus to inform some class that more items need to be loaded for your list and you also can use it to inform your ListView/ adapter that new items have been loaded, it will not do any network stuff like loading new items for you. You'll either have to do that on your own (off the main thread, e.g. AsyncTask) or use some library like this one.

When you're doing
EventBus.getDefault().post(new StartDownloadEvent()); nothing will happen except you have a class that receives the event and does the api call.

于 2015-03-12T23:36:18.123 回答