如何在水平RecyclerView中捕捉到LinearSnapHelper的特定位置?

Kis*_*nki 3 android kotlin android-recyclerview pagersnaphelper

如何在水平 RecyclerView 中捕捉到 LinearSnapHelper() 的特定位置?RecyclerView有一个函数scrolltoposition,它滚动到该位置,但没有将其保持在这个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.

在此输入图像描述

Vaj*_*han 5

将其添加到您想要滚动回收器视图的位置

 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));
        }
    }
Run Code Online (Sandbox Code Playgroud)

通过使用附加到回收器视图的 LinearSnap Helper

  var snapHelper = LinearSnapHelper()
    snapHelper.attachToRecyclerView(recyclerView)
Run Code Online (Sandbox Code Playgroud)

  • 注意:这是[这个早期的 Java 答案](/sf/answers/3476835211/) 的 Kotlin 端口。 (4认同)