How can I force or ensure that a Fragment gets recreated by FragmentStateAdapter?

24 views Asked by At

I recently found out that a Fragment in my app doesn't seem to be triggering any of its lifecycle methods. onCreateView, onResume, onAttach doesn't get triggered. I thought Navigation is just not functioning properly because of my use-case, then I realized the Fragment wasn't really directly interacting with Navigation but was being displayed using a ViewPager by another Fragment that actually can interact with Navigation. After finding this out, I tried the solutions I found looking around, but unfortunately they didn't work. And most of them is still using deprecated code so it might not really be practical to use them.

Here's what my code looks like:

private val fragmentPgLst: MutableList<Fragment> = mutableListOf(Frag1Fragment(), Frag2Fragment())

private fun setupViewPager() {
    val adapter = ViewPagerAdapter(ctx, fragmentPgLst)
    binding!!.vpgMain.adapter = adapter

    binding!!.navMain.setOnItemSelectedListener { item ->
        when (item.itemId) {
            R.id.nav_main_actuators -> binding!!.vpgMain.currentItem = 0
            R.id.nav_main_sensors -> binding!!.vpgMain.currentItem = 1
        }
        true
    }
}

class ViewPagerAdapter (fa: FragmentActivity, private val fragLst: MutableList<Fragment>) : FragmentStateAdapter(fa) {

    override fun getItemCount(): Int {
        return fragLst.size
    }

    override fun createFragment(position: Int): Fragment {
        return fragLst[position]
    }
}
1

There are 1 answers

0
rminaj On

Found the fix. After digging through the internal code, I found out that FragmentStateAdapter is saving the state of its Fragments, and I think that was what's keeping the Fragments from getting recreated. Then I found a way to stop FragmentStateAdapter from, I think, saving the state of its Fragment.

Here's the answer where I found the fix: https://stackoverflow.com/a/75624931/10464730