0

最初、listView には 20 個のアイテムがあります。ユーザーが一番下までスクロールしたときに、次の 20 項目で listView を更新する必要があります。これを実現するために ArrayAdapter を使用しています。listView の項目は、(AsyncTask ではなく) EventBus を使用して、startIndex と limit をパラメーターとして受け取る REST API から取得されます。

    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 に答える