androidandroid-recyclerviewandroid-nestedscrollview

Determine recycler item above center or below for a recycler view nested in NestedScrollView


Have a recycler view nested in NestedScrollView

<CoordinatorLayout>
<NestedScrollView>
<RelativeLayout>
<RecyclerView>

Trying to scroll to a particular item in recycler view with below code

val childOffset = recyclerView.y + recyclerView.getChildAt(index).top
binding.nestedScrollView.smoothScrollTo(0, childOffset.toInt())

Have to figure out if the scrolled element is in top part of center of screen or bottom part of screen. How to achieve this ?

  val outlocation = IntArray(2)
  viewHolder.getLocationOnScreen(outlocation)
  val displayOnTop = outLocation[1] > requireContext().resources.displayMetrics.heightPixels/2

This approach is not working as getLocationScreen value is not being consistent with scrolling.

What is the better way to achieve this ?


Solution

  • Was able to solve with below approach.

    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
    }