Junior — Middle
What are the advantages of using fragments compared to multiple Activities in Android applications?
sobes.tech AI
Answer from AI
Fragments in Android allow creating a more flexible and modular application architecture compared to using multiple Activities. Main advantages:
- Reusability of UI and logic. Fragments can be used in different Activities, reducing code duplication.
- Simplified UI management. Fragments enable dynamic UI changes within a single Activity, such as displaying different screens on tablets and phones.
- Better lifecycle management. Fragments have their own lifecycle, making it easier to manage state and resources.
- Navigation optimization. Using fragments reduces the number of Activities created, decreasing overhead and improving performance.
Example of using fragments to display a list and details in a single Activity:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (savedInstanceState == null) {
supportFragmentManager.beginTransaction()
.replace(R.id.container, ListFragment())
.commit()
}
}
}