Junior — Middle
What methods do you use to implement transitions between different fragments in an application?
sobes.tech AI
Answer from AI
In Android, fragment transitions are usually handled using FragmentManager and fragment transactions. The main methods are:
- FragmentTransaction.replace() — replaces the current fragment with a new one.
- FragmentTransaction.add() — adds a new fragment on top of the existing one.
- Navigation via Navigation Component — a modern approach where transitions are described in a navigation graph.
Example of replacing a fragment:
val fragment = NewFragment()
supportFragmentManager.beginTransaction()
.replace(R.id.fragment_container, fragment)
.addToBackStack(null) // allows returning back
.commit()
The Navigation Component simplifies navigation and manages transitions declaratively through nav_graph.xml.