在 NestedScrollView 中嵌套一个回收器视图
<CoordinatorLayout>
<NestedScrollView>
<RelativeLayout>
<RecyclerView>
尝试使用以下代码滚动到回收器视图中的特定项目
val childOffset = recyclerView.y + recyclerView.getChildAt(index).top
binding.nestedScrollView.smoothScrollTo(0, childOffset.toInt())
必须弄清楚滚动的元素是在屏幕中心的顶部还是屏幕的底部。 如何实现这一目标?
val outlocation = IntArray(2)
viewHolder.getLocationOnScreen(outlocation)
val displayOnTop = outLocation[1] > requireContext().resources.displayMetrics.heightPixels/2
此方法不起作用,因为 getLocationScreen 值与滚动不一致。
实现这一目标的更好方法是什么?
能够通过以下方法解决。
val viewHolder = recyclerView.layoutManager?.findViewByPosition(index)
if (viewHolder != null) {
val rect = Rect()
viewHolder.getHitRect(rect) //Gets the rectangle coordinates in parent view coordinates system of the recycler item
recyclerView.requestRectangleOnScreen(rect) //auto scroll and position item on screen with request Focus
val displayOnTop =
rect.bottom > (binding.nestedScrollView.top + binding.nestedScrollView.bottom) / 2
}