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?