Issues with Fragment State Restoration in Android 14 Using ViewPager2
I've been banging my head against this for hours. I'm encountering a frustrating issue with fragment state restoration in my app that's using ViewPager2 on Android 14. My setup involves two fragments that display images and text, and I expect the state to be preserved when navigating away and back. However, upon returning to the fragments, I notice that the images are being reset, and the text fields are empty, which is not the intended behavior. Initially, I have implemented the following code to set up the ViewPager2: ```kotlin class MainActivity : AppCompatActivity() { private lateinit var viewPager: ViewPager2 private lateinit var adapter: MyPagerAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) viewPager = findViewById(R.id.view_pager) adapter = MyPagerAdapter(this) viewPager.adapter = adapter } } ``` And my adapter looks like this: ```kotlin class MyPagerAdapter(fragmentActivity: FragmentActivity) : FragmentStateAdapter(fragmentActivity) { override fun getItemCount(): Int = 2 override fun createFragment(position: Int): Fragment { return if (position == 0) { ImageFragment.newInstance() } else { TextFragment.newInstance() } } } ``` Inside the fragments, I am using `onViewCreated()` to load images and set text. Hereβs a snippet from the `ImageFragment`: ```kotlin class ImageFragment : Fragment() { private lateinit var imageView: ImageView override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) imageView = view.findViewById(R.id.image_view) // Load image with Glide Glide.with(this).load(imageUrl).into(imageView) } } ``` Despite using `FragmentStateAdapter`, I suspect that the fragment states aren't being retained correctly because of how I manage the lifecycle. I've tried adding the following to prevent loss of state: ```kotlin override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) // Save state here, e.g., image URL or text } ``` But even with this, I still face the same issue. Additionally, I've checked the logs, and there's no indication of any exceptions or errors when navigating back. I just see a frustrating lack of retained state. Is there something I'm missing regarding the lifecycle management of fragments within ViewPager2? Any insight or alternative approaches would be greatly appreciated! I'm working on a API that needs to handle this. Any ideas what could be causing this?