Android:当用户使用eventBus和arrayadapter向下滚动到底部时,如何更新ListView

时间:2015-03-12 23:18:53

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

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

    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。

1 个答案:

答案 0 :(得分:0)

AsyncTaskEventBus是完全不同的两件事。 AsyncTask用于从主线程中执行操作,可能需要很长时间的事情(如网络内容),如果不在另一个线程上执行,则会阻塞主线程。 EventBus只是应用程序各部分之间的通信方式(活动,碎片等)。

虽然您确定可以使用EventBus通知某个班级需要为您的列表加载更多项目,您也可以使用它来通知您的ListView /适配器已加载新项目,它不会做任何网络的东西,比如为你装载新物品。 你要么必须自己做(在主线程之外,例如AsyncTask),要么使用像this之类的库。

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