2

I have three fragments

MainFragment // Fragment with ViewPager2 

ItemFragment // Fragment of the item of the adapter ViewPager2 that contains the RecyclerView 

PreviewFragment // Fragment to which I navigate after clicking on any RecyclerView item in the ItemFragment

When I go MainFragment -> PreviewFragment (exactly like that, not from ItemFragment) then on return back the ItemFragment is re-created from scratch. It is understandable because in OnCreateView I do this:

viewPager.adapter = MyAdapter(this)
// Add items

Tried saving MyAdapter like this:

private val adapter: MyAdapter by lazy { 
    MyAdapter(this)
}

But it leads to a crash, all the solutions described there did not help me.

I also tried to save fragments anywhere, in any repository and cache them there and then add them, but this leads to a bunch of leaks in the LeakCanary of ViewPager2.

In general, I would like to hear how this problem is solved, namely, you need to somehow save the state of the ViewPager2 items, perhaps they really need to be cached somewhere

P.S The main reason why the re-creation of fragments bothers me is that the scroll position of the RecyclerView gets lost

sakuraso13
  • 184
  • 1
  • 8

0 Answers0