简体   繁体   中英

How to load more items to the ListView with a LoaderManager

I am trying to load more items to the listview with LoadManager. But each time my listview updated and I can't see the old results. How can I see all results and load new one to the bottom part?

private OnScrollListener onScrollListener() {
return new OnScrollListener() {

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        int threshold = 1;
        int count = listView.getCount();

        if (scrollState == SCROLL_STATE_IDLE) {
            // is it good condition to load new data dynamically?
            if (listView.getLastVisiblePosition() >= count - threshold) {

                // startIndex is a start point for the query
                // default value is 0
                startIndex += 10;
                // this method format the URL using URI.Builder and change startIndex
                formatUrl(false, keywords, startIndex);

                // Clear the adapter
                mAdapter.clear();

                // I think the problem is here?! But how to fix it?!
                getLoaderManager().restartLoader(LOADER_ID, null, MainActivity.this);
            }
        }
    }

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

A good approach to deal with loading more items into listview is:

  • calling a loadMoreItems() function that loads the items into your items List, whenever the user reached the bottom of your listview .

  • using notifyDataSetChanged() method to notify the adapter that the items List has changed.

A simple implementation of the item-loading function:

    public loadMoreItems()
    {
       // your network logic here

      //append your items to your list
      for(Item item : fetchedItems)
      {
         items.add(item);
      }

      //inform the adapter about the data change
      adapter.notifyDataSetChanged();

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM