Junior — Middle
Describe how you manage fragments using FragmentManager in your project.
sobes.tech AI
Answer from AI
In Android, FragmentManager is used to manage fragments, allowing you to add, replace, remove, and control the fragment lifecycle.
Main operations:
- Adding a fragment:
supportFragmentManager.beginTransaction()
.add(R.id.container, MyFragment())
.commit()
- Replacing a fragment:
supportFragmentManager.beginTransaction()
.replace(R.id.container, AnotherFragment())
.commit()
- Adding to back stack: so the user can go back:
supportFragmentManager.beginTransaction()
.replace(R.id.container, AnotherFragment())
.addToBackStack(null)
.commit()
- Finding a fragment:
val fragment = supportFragmentManager.findFragmentByTag("tag")
In my projects, I use FragmentManager for dynamic UI management, for example, when navigating between screens within a single Activity, preserving state and ensuring a smooth user experience. It is also important to properly manage the fragment lifecycle to avoid memory leaks and errors during state restoration.