如何使用LoaderManager将更多项加载到ListView

时间:2017-06-12 04:27:00

标签: java android listview

我正在尝试使用LoadManager将更多项目加载到listview。但每次我的listview更新,我都看不到旧的结果。如何查看所有结果并将新的结果加载到底部?

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) {
    }
};

1 个答案:

答案 0 :(得分:0)

处理将更多项目加载到listview的好方法是:

  • 调用loadMoreItems()函数,只要用户到达listview的底部,就会将商品加载到商品列表中。

  • 使用notifyDataSetChanged()方法通知adapter项目列表已更改。

项目加载功能的简单实现:

    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();

    }