I am very glad that Google released ViewPager2 which is built on RecyclerView to solve a lot of issues that the old ViewPager has.
I quickly replaced my old ViewPager codes to ViewPager2:
Replace ViewPager with ViewPager2 in xml
Replace FragmentPagerAdapter(FragmentManager)
with FragmentStateAdapter(Fragment)
ViewPager setup is as below:
viewPager.adapter = fragmentAdapter
val mediator = TabLayoutMediator(tabLayout, viewPager, true) { tab, position ->
tab.text = fragmentAdapter.tabNames[position]
}
mediator.attach()
No other changes have been made.
After performing the above change, I realized a problem -
Now my ViewPager is an ordinary horizontal pager, and each fragment in my fragmentAdapter
has a vertical RecyclerView
.
I observed that when ever the scroll position of the RecyclerView is 0, my items in that RecyclerView cannot receive any click nor long click events, but it can be scrolled. Once it is scrolled, it can receive clicks again.*
Knowing that ViewPager2
is a RecyclerView
as well, is there something to do with nested RecyclerView?
It turns out it's probably a bug in either ConstraintLayout
or ViewPager2
.
The container of ViewPager2
was originally a ConstraintLayout
, and after I changed it to LinearLayout
, it simply worked.
I tried to reproduce the issue in a sample project but I can't reproduce even if I used ConstraintLayout
... So there must be some other conditions to make that happen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With