//自行替换自己的recyclerView val recyclerView = RecyclerView(this) val linearLayoutManager = LinearLayoutManager(this) recyclerView.layoutManager = linearLayoutManager //view的位置 var mutativePosition: Int //偏移 var rvMutativeOffset: Int recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) //获取layoutManager第一个view val view = recyclerView.layoutManager?.getChildAt(0) ?: return //获取第一个view当前所在的位置 mutativePosition = recyclerView.layoutManager?.getPosition(view)!! //获取第一个view当前所在的位置的偏移,垂直布局为top(从上到下排序) //获取第一个view当前所在的位置的偏移,横向布局为left(从左到右排序) recyclerView.layoutManager?.getChildAt(0)?.top?.let { rvMutativeOffset = it } } }) //然后滑动 linearLayoutManager.scrollToPositionWithOffset(mutativePosition, rvMutativeOffset)
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/280853.html