Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fragments in ViewPager2 does not respond to clicks if scroll position is 0

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:

  1. Replace ViewPager with ViewPager2 in xml

  2. Replace FragmentPagerAdapter(FragmentManager) with FragmentStateAdapter(Fragment)

  3. 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.

The problem

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?

like image 348
Sira Lam Avatar asked Jun 14 '19 01:06

Sira Lam


1 Answers

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.

like image 74
Sira Lam Avatar answered Oct 12 '22 21:10

Sira Lam