OnDraw Using Coordinates of Elements Scrolled Offscreen

Nathan Sokalski 4,116 Reputation points
2022-05-17T21:14:08.91+00:00

I have a RecyclerView (which uses a GridLayoutManager) inside a HorizontalScrollView. I do this to allow scrolling in both directions. When the user scrolls (either direction), I need to get the position of the selected element in the RecyclerView (I keep track of the selected element using an ItemClick event). I get the position using the GetLocationOnScreen method. This works fine when the element is onscreen, but when it gets scrolled offscreen, I end up with problems. What I do with the data from GetLocationOnScreen is use it in the OnDraw override of a custom view. However, because the values from GetLocationOnScreen are negative when the element is offscreen, the result does not display as expected. What should I do?

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,294 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 35,471 Reputation points Microsoft Vendor
    2022-05-18T02:29:02.763+00:00

    Hello,

    This works fine when the element is onscreen, but when it gets scrolled offscreen, I end up with problems.

    Referring to the documentation RecyclerView.LayoutManager, we could find that:

    A LayoutManager is responsible for measuring and positioning item views within a RecyclerView as well as determining the policy for when to recycle item views that are no longer visible to the user. By changing the LayoutManager a RecyclerView can be used to implement a standard vertically scrolling list, a uniform grid, staggered grids, horizontally scrolling collections and more. Several stock layout managers are provided for general use.

    It means that RecylerView has only views visible on the screen. All off-screen ViewHolders are detached and stored in RecyclerView.RecycledViewPool until they're on-screen again, and they are not laid out at all.

    That's the reason the issue occurs.

    If you want to disable recycling, you could use ViewHolder.setIsRecyclable(false); , however, doing so will cause RecycleView to lose its own characteristics and is not recommended

    Best Regards,

    Alec Liu.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.