如何实现RecyclerView页面滚动

3

我有一个需求,需要以一页为单位滚动Recyclerview。每个页面包含一个3x3项目的网格。

我使用了GridLayoutManager来实现网格,现在我正在尝试重写onScrolled()方法以实现按页滚动。我希望每次水平滚动显示3个项目,代表1页。

这是我的部分代码:

    recyclerView = (RecyclerView) rootView.findViewById(R.id.sub_category_list_recyclerview);
    recyclerView.setHasFixedSize(true);

    gridLayoutManager = new GridLayoutManager(getContext(), rowCount, LinearLayoutManager.HORIZONTAL, false);
    recyclerView.setLayoutManager(gridLayoutManager);

    adapter = new SubCategoryGridLayoutAdapter(new ArrayList<SubCategoryViewItem>());
    recyclerView.setAdapter(adapter);


    recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {


           int visibleItemCount = gridLayoutManager.getChildCount();
           int totalItemCount = gridLayoutManager.getItemCount();
           int  pastVisiblesItems = gridLayoutManager.findFirstVisibleItemPosition();
           int lastitemPos = gridLayoutManager.findLastVisibleItemPosition();



            if (dx > 0) {
                //Right Scrolling
                int moreItems = lastitemPos + 9;
                if (totalItemCount > moreItems){
                    gridLayoutManager.scrollToPositionWithOffset(moreItems, 0);
                }else {
                    gridLayoutManager.scrollToPositionWithOffset(totalItemCount, 0);
                }

            }
            if (dx < 0) {
                //Left Scrolling
                int lessItems = pastVisiblesItems + 9;
                if (lessItems < totalItemCount){
                    gridLayoutManager.scrollToPositionWithOffset(lessItems, 0);
                }else {
                    gridLayoutManager.scrollToPositionWithOffset(totalItemCount, 0);
                };
            }
        }
    });
1个回答

1

为了以后阅读此问题,支持库25.1.0添加了PageSnapHelper(用于模拟ViewPager - 仅逐项滚动)或LinearSnapHelper(移动到最靠近RecycleView中间的项目)。

使用方法很简单: PagerSnapHelper().attachToRecyclerView(rvYourRecycleViewName)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接