Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to snap to particular position of LinearSnapHelper in horizontal RecyclerView?

How can I snap to particular position for LinearSnapHelper() in horizontal RecyclerView? There is a function scrolltoposition for RecyclerView which scroll to that position but did not keep it in center for this snaphelper.

I am looking for something like below image. So when I set to particular position, it will keep it in center. I dont find anything related to select position for SnapHelper

i find this , but this doesn't help me. Any help would be appreciated.

enter image description here

like image 755
Kishan Solanki Avatar asked Aug 31 '25 22:08

Kishan Solanki


1 Answers

Add this where ever you want to scroll your recycler view

 recyclerView.scrollToPosition(position)
    recyclerView.post {
        var view = recyclerView.layoutManager?.findViewByPosition(position);
        if (view == null) {
          // do nothing
        }

        var snapDistance = snapHelper.calculateDistanceToFinalSnap(recyclerView.layoutManager!!, view!!)
        if (snapDistance?.get(0)   != 0 || snapDistance[1] != 0) {
            recyclerView.scrollBy(snapDistance?.get(0)!!, snapDistance?.get(1));
        }
    }

By using this LinearSnap Helper which is attached to your recycler view

  var snapHelper = LinearSnapHelper()
    snapHelper.attachToRecyclerView(recyclerView)
like image 155
Vajani Kishan Avatar answered Sep 05 '25 01:09

Vajani Kishan