'Create fragment in viewpager adapter when tab selected

There are two fragments inside viewPager. When the main fragment load the location permission code on the second fragment that work. Want that fragmen work when click the second tab. So I think I need to create this fragment when selected second tab. How can detect and do this?

OurHospitalFragment.kt

  viewPager2OurHospital.adapter = adapter
            viewPager2OurHospital.offscreenPageLimit = 1
            TabLayoutMediator(tabLayoutOurHospital, viewPager2OurHospital) { tab, position ->
                when (position) {
                    0 -> tab.text = getString(R.string.list)
                    1 -> tab.text = getString(R.string.map)
                }
            }.attach()

            tabLayoutOurHospital.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
                override fun onTabSelected(tab: TabLayout.Tab?) {
                    tab?.let {
                        viewPager2OurHospital.isUserInputEnabled = tab.position != 1
                    }
                }

                override fun onTabUnselected(tab: TabLayout.Tab?) {
                }

                override fun onTabReselected(tab: TabLayout.Tab?) {
                }
            })

OurHospitalASMViewPagerAdapter.kt

class OurHospitalViewPagerAdapter(fragmentManager: FragmentManager, lifecycle: Lifecycle) :
    FragmentStateAdapter(fragmentManager, lifecycle) {

    override fun getItemCount(): Int {
        return 2
    }

    override fun createFragment(position: Int): Fragment {
        return when (position) {
            0 -> HospitalListFragment()
            1 -> HospitalMapFragment()
            else -> Fragment()
        }
    }
}


Solution 1:[1]

I wrote this code line:

viewPager2OurHospital.offscreenPageLimit = ViewPager2.OFFSCREEN_PAGE_LIMIT_DEFAULT

instead of this:

viewPager2OurHospital.offscreenPageLimit = 1

and I get it what I want.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ahmet Yilmaz