确定嵌套在 NestedScrollView 中的回收器视图的中心上方或下方的回收器项目

问题描述 投票:0回答:1

在 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 值与滚动不一致。

实现这一目标的更好方法是什么?

android android-recyclerview android-nestedscrollview
1个回答
0
投票

能够通过以下方法解决。

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
}
© www.soinside.com 2019 - 2024. All rights reserved.