RecyclerView SnapHelper fails to show first/last items

前端 未结 4 1949
再見小時候
再見小時候 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:38

    I tried to implement a simple solution. Basically I checked if the first/last items are completely visible. If so, we don't need to perform the snap. See the solution below:

    class CarouselSnapHelper : LinearSnapHelper() {
    
        override fun findSnapView(layoutManager: RecyclerView.LayoutManager): View? {
            val linearLayoutManager = layoutManager as? LinearLayoutManager
                ?: return super.findSnapView(layoutManager)
    
            return linearLayoutManager
                .takeIf { isValidSnap(it) }
                ?.run { super.findSnapView(layoutManager) }
        }
    
        private fun isValidSnap(linearLayoutManager: LinearLayoutManager) =
            linearLayoutManager.findFirstCompletelyVisibleItemPosition() != 0 &&
                linearLayoutManager.findLastCompletelyVisibleItemPosition() != linearLayoutManager.itemCount - 1
    }
    

提交回复
热议问题