CodexBloom - Programming Q&A Platform

Fragment transition causes advanced patterns in ViewPager2 with nested Fragments on Android 14

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

I'm working with a peculiar scenario with `ViewPager2` when I try to navigate between fragments that contain nested fragments. Specifically, when I perform a transition from one fragment to another using `FragmentTransaction`, sometimes the nested fragments do not retain their state properly, leading to unexpected behavior like views being recreated unnecessarily or data loss. I am using Android 14 and `ViewPager2` with a `FragmentStateAdapter`. Here's a simplified version of my setup: ```kotlin class MyFragment : Fragment() { private lateinit var viewPager: ViewPager2 override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_my, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewPager = view.findViewById(R.id.viewPager) viewPager.adapter = MyPagerAdapter(this) } } class MyPagerAdapter(fragment: Fragment) : FragmentStateAdapter(fragment) { override fun getItemCount(): Int = 3 override fun createFragment(position: Int): Fragment { return when (position) { 0 -> FirstNestedFragment() 1 -> SecondNestedFragment() else -> ThirdNestedFragment() } } } ``` The scenario occurs when I navigate back from `SecondNestedFragment` to `FirstNestedFragment` and then to `ThirdNestedFragment`. The views in `FirstNestedFragment` sometimes do not populate their data correctly, and I get this behavior in the logs: `java.lang.IllegalStateException: Fragment already added: FirstNestedFragment`. I have tried calling `setRetainInstance(true)` in the fragments, but it hasn't resolved the question. I've also looked into using `FragmentManager`'s `findFragmentByTag()` but that seems cumbersome and doesn't guarantee the correct handling of the fragment lifecycle. Has anyone else encountered this scenario with `ViewPager2` and nested fragments? Is there a better approach to handling fragment transitions in this scenario? Any suggestions or workarounds would be greatly appreciated. This issue appeared after updating to Kotlin stable. I'd be grateful for any help.