CodexBloom - Programming Q&A Platform

Intermittent Crash on Launching Fragment with Custom Animation in Android 14

👀 Views: 26 đŸ’Ŧ Answers: 1 📅 Created: 2025-08-20
android fragment animation Kotlin

I'm testing a new approach and I'm trying to figure out I'm integrating two systems and I'm experiencing intermittent crashes when launching a fragment that has a custom enter/exit animation. The crash occurs sporadically and seems to be tied to the animation duration, as it works fine without animations. The crash log shows a `java.lang.IllegalStateException: Fragment already added` behavior when I call `add()` in the `FragmentTransaction` after the animations execute. Here's the relevant snippet where I'm setting up the fragment transaction: ```kotlin val fragment = MyCustomFragment() fragmentManager.beginTransaction() .setCustomAnimations(R.anim.enter, R.anim.exit) .add(R.id.fragment_container, fragment) .commit() ``` I have tried wrapping the `add()` call in a `try-catch` block, but it doesn't resolve the scenario since the fragment is sometimes already added, and the state seems to be unstable. The fragment also implements `setRetainInstance(true)` to manage its instance across configuration changes but might be conflicting with the animation lifecycle. I also verified that I'm not trying to add the fragment multiple times under any circumstances, as I've logged the fragment's state just before the transaction. Has anyone encountered a similar scenario, or does anyone know how to ensure the fragment transaction is cleanly managed during custom animations in Android 14? Any insights or workarounds would be greatly appreciated! I'm working in a Ubuntu 22.04 environment. Any suggestions would be helpful. This is for a microservice running on Debian. I'd really appreciate any guidance on this.