RecyclerView SnapHelper fails to show first/last items

前端 未结 4 1947
再見小時候
再見小時候 2021-02-08 19:10

I have a RecyclerView which is attached to a LinearSnapHelper to snap to center item. When I scroll to the first or last items, these items are not ful

4条回答
  •  再見小時候
    2021-02-08 19:44

    I found a less invasive answer:

    private class PagerSelectSnapHelper : LinearSnapHelper() {
    
        override fun findSnapView(layoutManager: RecyclerView.LayoutManager): View? {
            // Use existing LinearSnapHelper but override when the itemDecoration calculations are off
            val snapView = super.findSnapView(layoutManager)
            return if (!snapView.isViewInCenterOfParent(layoutManager.width)) {
                val endView = layoutManager.findViewByPosition(layoutManager.itemCount - 1)
                val startView = layoutManager.findViewByPosition(0)
    
                when {
                    endView.isViewInCenterOfParent(layoutManager.width) -> endView
                    startView.isViewInCenterOfParent(layoutManager.width) -> startView
                    else -> snapView
                }
            } else {
                snapView
            }
        }
    
        private fun View?.isViewInCenterOfParent(parentWidth: Int): Boolean {
            if (this == null || width == 0) {
                return false
            }
            val parentCenter = parentWidth / 2
            return left < parentCenter && parentCenter < right
        }
    }
    

提交回复
热议问题