Junior
Why are fragments used if Activity already exists?
sobes.tech AI
Answer from AI
Fragments allow creating modular and reusable user interface components within an Activity.
Main advantages:
- UI Flexibility: Easily create different UI configurations for various screen sizes and orientations (tablet vs phone).
- Reusability: The same fragment can be used in multiple Activities or multiple times within one Activity.
- Lifecycle management: Fragments have their own lifecycle, which is related to but managed separately from the Activity's lifecycle.
- Navigation: Convenient for implementing complex navigation flows within a single Activity (e.g., with Navigation Component).
- State management: Allow preserving part of the UI state during configuration changes or navigation within the Activity.
Example of usage for a tablet (master-detail):
| Left panel (list of items) | Right panel (details of selected item) |
|---|---|
ItemListFragment |
ItemDetailFragment |
Example code for adding a fragment to an Activity:
// In Activity
supportFragmentManager.beginTransaction()
.replace(R.id.fragment_container, YourFragment.newInstance())
.commit()