简体   繁体   中英

SnapHelper issue with first and Last item

I am using Recyclerview with PageSnapHelper to create an Image carousel.

在此处输入图像描述<\/a>

RecyclerView is inside nested scrollview.

 override fun findTargetSnapPosition(layoutManager: RecyclerView.LayoutManager, velocityX: Int, velocityY: Int): Int {

    if (layoutManager !is RecyclerView.SmoothScroller.ScrollVectorProvider) {
        return RecyclerView.NO_POSITION
    }

    val currentView = findSnapView(layoutManager) ?: return RecyclerView.NO_POSITION

    val layoutManager = layoutManager as LinearLayoutManager

    val position1 = layoutManager.findFirstVisibleItemPosition()
    val position2 = layoutManager.findLastVisibleItemPosition()

    var currentPosition = layoutManager.getPosition(currentView)



    if (velocityX > 500) {
        currentPosition = position2
    } else if (velocityX < 500) {
        currentPosition = position1
    }

    return if (currentPosition == RecyclerView.NO_POSITION) {
        RecyclerView.NO_POSITION
    } else currentPosition

}

If i got you right, you need to override LinearSnapHelper instead, cause your item views are not full screened. For achiving focusing on first\/last items you need to override findSnapView next way(note that this snippet only appliable when RecyclerView.layoutmanager is LinearLayoutManager):

fun RecyclerView.setLinearSnapHelper(isReversed: Boolean = false) {
object : LinearSnapHelper() {

    override fun findSnapView(layoutManager: RecyclerView.LayoutManager?): View? {
        val firstVisiblePosition = (layoutManager as LinearLayoutManager).findFirstCompletelyVisibleItemPosition()
        val lastVisiblePosition = layoutManager.findLastCompletelyVisibleItemPosition()
        val firstItem = 0
        val lastItem = layoutManager.itemCount - 1
        return when {
            firstItem == firstVisiblePosition -> layoutManager.findViewByPosition(firstVisiblePosition)
            lastItem == lastVisiblePosition -> layoutManager.findViewByPosition(lastVisiblePosition)
            else -> super.findSnapView(layoutManager)
        }
    }
}.apply { attachToRecyclerView(this@setLinearSnapHelper) }

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