Android ListView在滚动到Bottom时动态加载更多项目(来自MysqlDatabase)

时间:2015-06-24 12:13:10

标签: listview android-listview expandablelistview

滚动时如何检测列表结尾并触发从WEB请求向ListView加载更多数据

如果从WEB服务器加载数据并且列表很大,那么实际的解决方案是加载一定数量,如果用户滚动到列表的末尾,请加载一些并继续运行直到加载完整清单

1 个答案:

答案 0 :(得分:0)

您可以向ListView添加分页侦听器: 1.实施AbsListView.OnScrollListener,例如,您可以创建

抽象类InfiniteListViewPaging

 public abstract class InfiniteListViewPaging implements AbsListView.OnScrollListener {

    private static final String TAG = InfiniteListViewPaging.class.getName();
    public ListView mListView;
    public View mFooterView;
    private boolean mCanLoadMore;
    private boolean mIsLoading;

    /**
     * Should be created before setting the adapter on the {@code listView} as this sets the
     * {@link android.widget.ListView#addFooterView(android.view.View)} on it.
     * @param context
     * @param listView
     */
    public InfiniteListViewPaging(Context context, ListView listView) {
        mFooterView = View.inflate(context, R.layout.footer_list_view, null);
        mListView = listView;
        listView.addFooterView(mFooterView, null, false);
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                         int totalItemCount) {
        boolean lessThanOneScreenLeftToScrollDown = (totalItemCount - 2 * visibleItemCount) <= firstVisibleItem;
        if (mCanLoadMore && !mIsLoading && lessThanOneScreenLeftToScrollDown) {
            Log.d(TAG, "Load Next Page!");
            mIsLoading = true;
            loadMore();
        }
    }

    public void setCanLoadMore(boolean canLoadMore) {
        mCanLoadMore = canLoadMore;
        mFooterView.setVisibility(canLoadMore ? View.VISIBLE : View.GONE);
    }

    public abstract void loadMore();

    public void hasFinishedLoading() {
        mIsLoading = false;
    }
  1. 然后在您的Activity(或Fragment)中初始化ListView set

    mListPaging = new InfiniteListViewPaging(this, getListView()) {
                        @Override
                      public void loadMore() {
                           loadMore();
                       } 
    }; 
    mListView.setOnScrollListener(mListPaging);