How to programmatically snap to position on Recycler view with LinearSnapHelper

前端 未结 3 1109
执念已碎
执念已碎 2021-02-07 05:40

I have implemented a horizontal recyclerView with LinearSnapHelper, to implement a UI input that selects a particular configuration. Kinda like the old school number picker/sele

3条回答
  •  自闭症患者
    2021-02-07 06:14

    More general solution:

    1. First scroll RecyclerView to make target item visible.
    2. Than, take the object of target View and use SnapHelper to determine distance for the final snap.
    3. Finally scroll to target position.

    NOTE: This works only because programmatically you are scrolling at the exact position & covering the missing distance by exact value using scrollBy instead of doing smooth scrolling

    Code snippet:

    mRecyclerView.scrollToPosition(selectedPosition);
    mRecyclerView.post(() -> {
            View view = mLayoutManager.findViewByPosition(selectedPosition);
            if (view == null) {
                Log.e(WingPickerView.class.getSimpleName(), "Cant find target View for initial Snap");
                return;
            }
    
            int[] snapDistance = mSnapHelper.calculateDistanceToFinalSnap(mLayoutManager, view);
            if (snapDistance[0] != 0 || snapDistance[1] != 0) {
                mRecyclerView.scrollBy(snapDistance[0], snapDistance[1]);
            }
        }
    });
    

提交回复
热议问题