How to programmatically snap to position on Recycler view with LinearSnapHelper

前端 未结 3 1060
执念已碎
执念已碎 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]);
            }
        }
    });
    
    0 讨论(0)
  • 2021-02-07 06:14

    Try calling smoothScrollToPosition on the RecyclerView object, and passing the position index (int)

    mRecyclerView.smoothScrollToPosition(position);
    

    Worked for me with a LinearLayoutManager and LinearSnapHelper. It animates the initial scroll, but at least snaps the item in position.

    This is my first post on the stack, hope it helps :)

    0 讨论(0)
  • 2021-02-07 06:35

    I have a recyclerView which I have added padding at the left and right with dummy views in the adapter. So that the first "actual" item can be snapped to.

    I couldn't get smoothScrollToPosition(0) to work though for the initial snap. I used the following

    recycler.scrollBy(snapHelper.calculateDistanceToFinalSnap(binding.recycler.getLayoutManager(), recycler.getChildAt(1))[0], 0);
    

    Isn't the nicest looking way, but seems to work!

    0 讨论(0)
提交回复
热议问题