Home > OS >  ViewPager2 : Initialize fragments only when they are visiblee, and then keep them initialized
ViewPager2 : Initialize fragments only when they are visiblee, and then keep them initialized

Time:02-03

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?

CodePudding user response:

I couldn't find a solution for this, But anyway what is your problem with this behaviours? If you need a call back for when the fragment is visible you can use onResume callback. And if you want to onResume code not call twice you can set a variable (boolean) to true in the end of onResume and check it's value at first line of onResume.

  •  Tags:  
  • Related