Junior — Middle
Explain the concept of fragments and their role in application architecture.
sobes.tech AI
Answer from AI
Fragments are components of the user interface in Android that represent a part of the screen or a behavior of the application. They allow creating flexible and adaptive interfaces, especially on devices with different screen sizes.
Role of fragments:
- Enable breaking down the UI into independent parts that can be reused.
- Facilitate management of the lifecycle of UI parts.
- Allow dynamically adding, replacing, or removing parts of the UI during app operation.
For example, on a tablet, you can display a list and details simultaneously (two fragments on one screen), while on a phone, you can switch between them.
Example of using a fragment in Android:
class ExampleFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_example, container, false)
}
}
Fragments are managed by activities and interact with them, making the app architecture more modular and easier to maintain.