简体   繁体   中英

RecyclerView PagerSnapHelper Snap on Start/Top instead of center Android

I am using a vertical recycler view and have attached a pagerSnapHelper.it works fine and snaps the items to the center position but I want it to snap to the start (top side). I don't want to use linearSnapHelper as it does not work the way I want. nor GravitySnapHelper will work as it extends linearSnapHelper.if you can share a similar class with PagerSnapHelper extended it will be great

So I achieved a working solution by using LinearSnapHelper. using a library to snap to the top

the library - https://github.com/rubensousa/GravitySnapHelper

In order to achieve scroll similar to pager snap helper I used below code

 // remember to initialize snaphelper
 snapHelper = object : GravitySnapHelper(Gravity.TOP){
        override fun findTargetSnapPosition(
            layoutManager: RecyclerView.LayoutManager,
            velocityX: Int,
            velocityY: Int
        ): Int {
            val centerView = findSnapView(layoutManager) ?: return RecyclerView.NO_POSITION
            val position = layoutManager.getPosition(centerView)
            var targetPosition = -1
            if (layoutManager.canScrollHorizontally()) {
                targetPosition = if (velocityX < 0) {
                    position - 1
                } else {
                    position + 1
                }
            }
            if (layoutManager.canScrollVertically()) {

               // Log.d("debug", "velocityY $velocityY")
                targetPosition = if (velocityY < 0) {
                    position - 1
                } else {
                    position + 1
                }
            }
            val firstItem = 0
            val lastItem = layoutManager.itemCount - 1
            targetPosition = Math.min(lastItem, Math.max(targetPosition, firstItem))
            return targetPosition
        }



    }

    // lower the value higher the speed of scroll 
    // default is 100f
    snapHelper.scrollMsPerInch = 40f

    snapHelper.attachToRecyclerView(binding?.yourRecyclerView)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM