1

For the same reason described in this SO question, I want to get access to the RecyclerView inside a ViewPager2. This RecyclerView is not exposed in any way.

I kept the title deliberately broad, because my intention of this question is not to solve a specific question; the problem is solved. The ViewPager2 is mere an example. I want to know if there is an objective better long term approach.

One could:

  • Use reflection to access the property mRecyclerView
  • Find and cast a view child to RecyclerView.
  • (Do not use ViewPager2, but use an RecyclerView and add a layout manager, snapping and paging manually; deemed out of scope for this question)

I'd say:

  • The RV is fetched once, so cost is negligible
  • ViewPager2 is stable enough, that at least the name of the property or the amount of child views will not change.
  • Both solutions hardcode knowledge of ViewPager2 in the app it should not know

In this case, is one better than the other?

Michiel
  • 767
  • 4
  • 19
  • 5
    "ViewPager2 is stable enough, that at least the name of the property or the amount of child views will not change" -- I would not make either of those assumptions, between versions of the library. IMHO, a more stable assumption is: `ViewPager2` only has one `RecyclerView`. So, find the first `RecyclerView` child of `ViewPager2`. If you want to be really safe, find *all* `RecyclerView` children of the `ViewPager2`, and if the count is not 1, do something to warn you that the new version of the library that you adopted broke this assumption. – CommonsWare Oct 22 '21 at 11:51
  • Makes a lot of sense. I'll find a child view and add a test checking my assumption – Michiel Oct 22 '21 at 13:04

0 Answers0