CodexBloom - Programming Q&A Platform

ViewPager2 Not Retaining State of Fragments Across Page Swipes in Android 14

👀 Views: 22 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-17
android viewpager2 fragment lifecycle kotlin

I'm trying to figure out I'm prototyping a solution and I'm facing an issue with ViewPager2 where the fragments don't seem to retain their state when swiping back and forth. I'm using Android 14 and the fragments in my ViewPager2 are displaying forms that the user can fill out. However, when I swipe away from a fragment and come back, all the user input is lost, which is not the behavior I expect. I tried using `FragmentStateAdapter`, which should theoretically handle the fragment lifecycle, but I'm still seeing this issue. I implemented my `FragmentStateAdapter` like this: ```kotlin class MyFragmentStateAdapter(fragmentActivity: FragmentActivity) : FragmentStateAdapter(fragmentActivity) { override fun getItemCount(): Int = 3 override fun createFragment(position: Int): Fragment { return when (position) { 0 -> FormFragment.newInstance() // Form 1 1 -> FormFragment.newInstance() // Form 2 2 -> FormFragment.newInstance() // Form 3 else -> throw IllegalStateException("Unexpected position: $position") } } } ``` In each `FormFragment`, I save the user input in `onSaveInstanceState` and restore it in `onCreateView`: ```kotlin class FormFragment : Fragment() { private var userInput: String? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { if (savedInstanceState != null) { userInput = savedInstanceState.getString("user_input") } // Inflate the layout and set the input if it exists } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putString("user_input", userInput) } } ``` However, every time I swipe to a different fragment and go back, the input fields are empty. I've also tried overriding `setUserVisibleHint` to save and restore the state, but it didn't make a difference. I've checked the lifecycle methods, and it looks like `onCreateView` is being called for fragments that I thought should have their state retained. Am I missing something in the configuration of the adapter, or is there a better approach to retain the fragment states? Any insights would be appreciated! The project is a REST API built with Kotlin. Has anyone dealt with something similar? For reference, this is a production application. Is there a better approach?