I have 4 fragments managed using ViewPager2.
I want to initialize each fragment only when i open it for the first time, that's means when i open the app, only the first fragment get initialized, and the second fragment will be initialized only when i navigate to it.
This seems the default behavior for the viewpager2 when i don't do any special configuration.
But what I want to do is not lose the instance of the first fragment when I navigate to second fragment.
I tried to use viewpager.isUserInputEnabled = 4 (or 1). this function keep fragments initialized and don't lose their instances. but it initialize all fragments at once, and I only want to initialize them when they are visible.
this is my adapter
class HomeAdapter(fragmentActivity : FragmentActivity) : FragmentStateAdapter(fragmentActivity)
{
override fun getItemCount() : Int = 4
override fun createFragment(position : Int) : Fragment
{
return when(position)
{
0 -> SearchMissionContainerFragment.instance()
1 -> MissionHistoryFragment.instance()
2 -> PaymentContainerView.instance()
else -> SettingsFragment.instance()
}
}
}
and this is the initialization part
binding.viewpager.offscreenPageLimit = 1
binding.viewpager.isUserInputEnabled = false
binding.viewpager.adapter = HomeAdapter(this)
Any solution please?