RecyclerView SnapHelper fails to show first/last items

前端 未结 4 1950
再見小時候
再見小時候 2021-02-08 19:10

I have a RecyclerView which is attached to a LinearSnapHelper to snap to center item. When I scroll to the first or last items, these items are not ful

4条回答
  •  日久生厌
    2021-02-08 19:43

    I know I am late but I want to suggest an simple solution written in Java code:

    Create CustomSnapHelper class:

     public class CustomSnapHelper extends LinearSnapHelper {
            @Override
            public View findSnapView(RecyclerView.LayoutManager layoutManager) {
                if(layoutManager instanceof LinearLayoutManager){
                    LinearLayoutManager linearLayoutManager = (LinearLayoutManager) layoutManager;
                    if(needToDoSnap(linearLayoutManager)==false){
                        return null;
                    }
                }
                return super.findSnapView(layoutManager);
            }
            public boolean needToDoSnap(LinearLayoutManager linearLayoutManager){
                return linearLayoutManager.findFirstCompletelyVisibleItemPosition()!=0&&linearLayoutManager.findLastCompletelyVisibleItemPosition()!=linearLayoutManager.getItemCount()-1;
            }
        }
    

    Attach an object of CustomSnapHelper for recycler view:

    CustomSnapHelper mSnapHelper = new CustomSnapHelper();
    mSnapHelper.attachToRecyclerView(mRecyclerView);
    

提交回复
热议问题