SnapHelper Item Position

I try to use this code with a PagerSnapHelper to mimic the pager behaviour and it was useful but i found some corner cases to solve, if you move fast from the last page to the first one and keep swapping until see the boundarie then the IDLE state doesnt happen and you lose your index. to solve that I move out the position from the IF and add a extra condition for this corner case.

 override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
             super.onScrollStateChanged(recyclerView, newState)
             val centerView = snapHelper.findSnapView(mLayoutManager)
             val pos = mLayoutManager.getPosition(centerView!!)
             if (newState == RecyclerView.SCROLL_STATE_IDLE || (pos == 0 && newState == RecyclerView.SCROLL_STATE_DRAGGING)) {
                 Log.d("BINDING", "positionView SCROLL_STATE_IDLE: $pos")
             }
         }

Code is in kotlin hope it helps


I used this on a project that had a RecyclerView with SnapHelper, not sure if it is what you want.

mRecyclerView.setHasFixedSize(true);

    // use a linear layout manager
    mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
    mRecyclerView.setLayoutManager(mLayoutManager);

    // specify an adapter (see also next example)
    mAdapter = new DemoSlidesAdapter(getApplicationContext());
    mRecyclerView.setAdapter(mAdapter);

    final SnapHelper snapHelper = new LinearSnapHelper();
    snapHelper.attachToRecyclerView(mRecyclerView);

    mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            if(newState == RecyclerView.SCROLL_STATE_IDLE) {
                View centerView = snapHelper.findSnapView(mLayoutManager);
                int pos = mLayoutManager.getPosition(centerView);
                Log.e("Snapped Item Position:",""+pos);
            }
        }
    });