CodexBloom - Programming Q&A Platform

Fragment Lifecycle Confusion with ViewPager2 and TabLayout on Android 14

👀 Views: 13 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-12
android viewpager2 fragment kotlin

I can't seem to get I tried several approaches but none seem to work... I'm experiencing unexpected behavior when using `Fragment` within a `ViewPager2` along with `TabLayout` on Android 14. Specifically, the fragments seem to be losing their view state when swiped away and then back. I have set up my `ViewPager2` with a `FragmentStateAdapter`, but the fragments aren't retaining data as expected. I've tried implementing the `onSaveInstanceState()` method in my fragments to save their state, but it doesn't seem to have any effect when I return to the fragment after swiping. Here's a simplified version of my setup: ```kotlin class MyFragment : Fragment() { private var myData: String? = null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { if (savedInstanceState != null) { myData = savedInstanceState.getString("my_key") } return inflater.inflate(R.layout.fragment_my, container, false) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putString("my_key", myData) } } ``` In my `FragmentStateAdapter`, I initialize the fragments like this: ```kotlin class MyPagerAdapter(fragmentActivity: FragmentActivity) : FragmentStateAdapter(fragmentActivity) { override fun getItemCount(): Int = 3 override fun createFragment(position: Int): Fragment { return MyFragment() } } ``` I've also tried using `setRetainInstance(true)` in my fragment's `onCreate()`, but that doesn't seem to make any difference either. I checked the logs, and there are no errors being thrown. However, when I swipe away from the fragment and return, `myData` is always null. Is there something I'm missing in my implementation, or is this a known scenario with `ViewPager2` on Android 14? Any insights would be greatly appreciated! Has anyone dealt with something similar?