Issues with ViewPager2 and FragmentStateAdapter Not Retaining Fragment State in Android 13
I need help solving I'm having trouble with Quick question that's been bugging me - This might be a silly question, but I'm encountering an issue with `ViewPager2` when using `FragmentStateAdapter` in an Android 13 application... The fragments are supposed to retain their state when I navigate back and forth, but I'm finding that they are being recreated each time I swipe. This leads to loss of data entered in each fragment, which is problematic for my use case. I've implemented the `FragmentStateAdapter` like this: ```kotlin class MyPagerAdapter(fragmentActivity: FragmentActivity) : FragmentStateAdapter(fragmentActivity) { override fun getItemCount(): Int = 3 override fun createFragment(position: Int): Fragment { return when (position) { 0 -> FirstFragment() 1 -> SecondFragment() else -> ThirdFragment() } } } ``` In my `Activity`, I set up the `ViewPager2` like this: ```kotlin class MyActivity : AppCompatActivity() { private lateinit var viewPager: ViewPager2 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_my) viewPager = findViewById(R.id.viewPager) viewPager.adapter = MyPagerAdapter(this) } } ``` Despite this setup, when I swipe to another fragment and return, the data inputted into the `EditText` fields is lost. I've confirmed that I'm using `FragmentStateAdapter` correctly according to the documentation. I've also checked if the fragments are being retained in the fragment manager, but they don't appear to be. I tried overriding `setRetainInstance(true)` in the fragments, but it didn't seem to help either. Additionally, I'm noticing some logs indicating that fragments are being detached and reattached: ``` 2023-10-10 12:34:56.789 12345-12345/? E/FragmentManager: Detaching fragment... 2023-10-10 12:34:56.790 12345-12345/? E/FragmentManager: Re-attaching fragment... ``` Is there a specific configuration or implementation detail that I might be missing? Any guidance on how to retain the state of these fragments while navigating within the `ViewPager2` would be greatly appreciated. Thanks! Is there a better approach? How would you solve this? Hoping someone can shed some light on this. Any ideas how to fix this? I'm on Windows 11 using the latest version of Kotlin. Any ideas how to fix this?