ViewPager2 reuse fragments when popbackstack is called
Asked Answered
M

2

1

I have main fragment with ViewPager2 that contains other fragments. Each child fragment can open another detail fragment (main fragment replaced with details fragment). When I go back to from detail fragment, ViewPager2 recreate all child fragments.

If I try to reuse the adapter (FragmentStateAdapter):

if (pagerAdapter == null) {
        pagerAdapter = Adapter(this)
        binding.viewPager.adapter = pagerAdapter
    }else{
        binding.viewPager.adapter = pagerAdapter
    }

I got crash:

java.lang.IllegalArgumentException at androidx.core.util.Preconditions.checkArgument(Preconditions.java:38) at androidx.viewpager2.adapter.FragmentStateAdapter.onAttachedToRecyclerView(FragmentStateAdapter.java:132) at androidx.recyclerview.widget.RecyclerView.setAdapterInternal(RecyclerView.java:1209) at androidx.recyclerview.widget.RecyclerView.setAdapter(RecyclerView.java:1161) at androidx.viewpager2.widget.ViewPager2.setAdapter(ViewPager2.java:461)

How to avoid creating new fragment every time?

Moratorium answered 24/4, 2022 at 10:51 Comment(2)
I have some problemWooded
Check for this link -[https://mcmap.net/q/376080/-expected-the-adapter-to-be-39-fresh-39-while-restoring-state]Creamery
W
1

I solved the problem. I init adapter every time in onCreate, before I used lazy for init adapter.

logVP2.adapter = SummaryDetailsPageAdapter(childFragmentManager, lifecycle).apply { setData(args?.list) }

Wooded answered 7/6, 2022 at 23:15 Comment(1)
this should be marked as the right answer. but why this happen really? what is the problem with lazy?Tawnatawney
B
0

The problem really lies in lazy initialization. Perhaps someone will find a useful solution, without lazy initialization and laterinit:

private var _profileAdapter: ProfileVpAdapter? = null

private val profileVPAdapter: ProfileVpAdapter
        get() = _profileAdapter ?: ProfileVpAdapter(this).also {
            _profileAdapter = it
        }

override fun onDestroyView() {
        super.onDestroyView()
        _profileAdapter = null
    }

Use in fragment profileVPAdapter

Bolduc answered 15/5 at 5:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.