Introduction To Fragments in Android
Introduction To Fragments in Android
Fragments in
Android
Fragments are modular pieces of an Android app's user interface that can
be reused and rearranged dynamically. They provide a way to create
reusable UI components that can be easily swapped in and out of an app's
layout, enabling a more flexible and responsive design.
MA by Muhammad Sabran
What are Fragments?
1 Modular UI 2 Lifecycle 3 Reusability
Components Management Fragments can be easily
Fragments are self- Fragments have their own reused across different
contained pieces of UI lifecycle that is tied to the parts of an app,
that can be added, activity they are hosted promoting code reuse
removed, or replaced in, allowing for more fine- and consistency.
within an app's layout. grained control over the
user interface.
Lifecycle of Fragments
1 Creation
Fragments are created and their views are inflated when the hosting activity is
created.
2 Activation
Fragments become active when their hosting activity is resumed, and can start
interacting with the user.
3 Deactivation
Fragments become inactive when their hosting activity is paused, and should
stop any ongoing interactions.
Fragment Transactions
Adding Fragments Replacing Fragments Removing Fragments
Pop
2 Fragments can be removed from the backstack, allowing the user to navigate
back to previous states of the UI.
Retain
3 Fragments can retain their state when popped from the backstack, providing a
seamless user experience.
Advantages of using Fragments
Reusability Modularity
Fragments can be easily reused across Fragments provide a modular and flexible way
different parts of an app, promoting code to build user interfaces, allowing for dynamic
reuse and consistency. updates and rearrangements.