Home » Android » listview – Android prevent nested recyclerview from automatically repositioning

listview – Android prevent nested recyclerview from automatically repositioning

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have a ViewPager as an item in a Linear Layout, with each item in the view pager containing a RecyclerView. The problem is, whenever the page initially loads, or when I change pages on the ViewPager, the view automatically scrolls so the beginning of the recycler view is the top of the screen, rather than staying how it is.

A .gif of the issue is here. Note I am not scrolling down, that is the automatic repositioning.

How can I prevent the view from automatically repositioning to the start of the recycler view?

How to&Answers:

you can add this attribute to your linear layout. The Linear Layout direct child of your scrollView.

    android:descendantFocusability="blocksDescendants"

Answer:

We have a similar problem. We have a vertical RecyclerView. Each item of this vertical RecyclerView contains an horizontal RecyclerView, like in the Android TV app.

When we upgraded the support libs from 23.4.0 to 24.0.0 the automatic scroll suddenly appeared. In particular, when we open an Activity and we then go back, the vertical RecyclerView scrolls up so that the current horizontal RecyclerView row does not get cut and the row is displayed completely.

Adding android:descendantFocusability="blocksDescendants" fixes the issue.

However, I’ve found another solution, which also works. In our case the vertical RecyclerView is contained inside a FrameLayout. If I add android:focusableInTouchMode="true" to this FrameLayout, the problem goes away.

There’s even a third solution mentioned here, which basically consists on calling setFocusable(false) on the child/inner RecyclerViews. I haven’t tryied this.

By the way, there is an open issue on the AOSP.

Answer:

I guess that the problem is not on your recyclerview but on your viewpager. ViewPager has setOffscreenPageLimit method that used to define offscreen page of your fragment attached to viewpager. if you have 3 fragment attached on viewpager, you can set its parameter like this

viePager.setOffscreenPageLimit(3); 

Whenever you change the pager page, its fragment would still on last state.