CodexBloom - Programming Q&A Platform

Unexpected 'Fragment already added' handling when using Multi-Module Architecture in Android 14

👀 Views: 194 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-06
android fragment navigation-component Kotlin

I've been banging my head against this for hours. I'm sure I'm missing something obvious here, but I've searched everywhere and can't find a clear answer..... I'm working with an scenario where I get a 'Fragment already added' exception when navigating between fragments in my multi-module architecture app on Android 14. I'm using the Navigation Component to handle fragment transactions. The behavior occurs when I try to navigate from a parent fragment to a child fragment that has already been added to the FragmentManager. I've ensured that I'm calling `replace()` instead of `add()` in my navigation actions, but the scenario continues. Here's a simplified version of my navigation code: ```kotlin val childFragment = ChildFragment() if (childFragment.isAdded.not()) { parentFragmentManager.beginTransaction() .replace(R.id.fragment_container, childFragment) .addToBackStack(null) .commit() } else { Toast.makeText(context, "ChildFragment is already added", Toast.LENGTH_SHORT).show() } ``` I've also checked the Fragment lifecycle and confirmed that I'm not trying to add the fragment again under any circumstances. The child fragment is being created only once, but the transaction seems to attempt to re-add it somehow. I'm using the latest version of the Navigation Component and Jetpack libraries, and my Gradle dependencies are as follows: ```gradle dependencies { implementation 'androidx.navigation:navigation-fragment-ktx:2.5.3' implementation 'androidx.navigation:navigation-ui-ktx:2.5.3' } ``` I've tried using `FragmentManager.findFragmentById()` to check the existence of the fragment before performing the transaction, but that didn't resolve the scenario either. Any insights or suggestions on how to properly manage fragment transactions in a multi-module setup like this would be greatly appreciated! For context: I'm using Kotlin on Windows. Any help would be greatly appreciated!