How to implement Endless scrolling using StaggeredLayoutManager

前端 未结 4 2028
暖寄归人
暖寄归人 2021-02-07 04:49

I already tried to implement the endless scrolling for LinearLayoutManager and it is successful and tried to copy the LinearLayoutManager implementation to StaggeredGridLayoutMa

4条回答
  •  一整个雨季
    2021-02-07 05:08

    This is my implementation of a ScrollListener.

    Here's my code for implementing the ScrollListener:

    private EndlessScrollListener scrollListener =
        new EndlessScrollListener(new EndlessScrollListener.RefreshList() {
            @Override public void onRefresh(int pageNumber) {
                //Here you can execute server connection or anything else to update data and present with Recycler view
                // Notice: It is sync method
    
            }
        });
    
    recyclerView.addOnScrollListener(scrollListener);
    

    Custom ScrollListener class:

    class EndlessScrollListener extends RecyclerView.OnScrollListener {
        private boolean isLoading;
        private boolean hasMorePages;
        private int pageNumber = 0;
        private RefreshList refreshList;
        private boolean isRefreshing;
        private int pastVisibleItems;
    
    
    
        public EndlessScrollListener(RefreshList refreshList) {
            this.isLoading = false;
            this.hasMorePages = true;
            this.refreshList = refreshList;
        }
    
        @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            StaggeredGridLayoutManager manager =
                (StaggeredGridLayoutManager) recyclerView.getLayoutManager();
    
            int visibleItemCount = manager.getChildCount();
            int totalItemCount = manager.getItemCount();
            int[] firstVisibleItems = manager.findFirstVisibleItemPositions(null);
            if (firstVisibleItems != null && firstVisibleItems.length > 0) {
                pastVisibleItems = firstVisibleItems[0];
            }
    
            if ((visibleItemCount + pastVisibleItems) >= totalItemCount && !isLoading) {
                isLoading = true;
                if (hasMorePages && !isRefreshing) {
                    isRefreshing = true;
                    new Handler().postDelayed(new Runnable() {
                        @Override public void run() {
                            refreshList.onRefresh(pageNumber);
                        }
                    }, 200);
                }
            } else {
                isLoading = false;
            }
        }
    
        public void noMorePages() {
            this.hasMorePages = false;
        }
    
        public void notifyMorePages() {
            isRefreshing = false;
            pageNumber = pageNumber + 1;
        }
    
    
    
        public interface RefreshList {
            void onRefresh(int pageNumber);
        }
    }
    

提交回复
热议问题