Android Fragment
Android Fragment:
Fragments are small building blocks in android which show part of the activity then can be reused elsewhere or reused in the same activity.
They were introduced to accommodate more agile and versatile UI paradigms, particularly useful when working on wide-screen devices such as tablets.
Modularity:
Components can be snapped into fragments that enables you to make the components to be reusable in the user interfaces.
Usually they can be used together in the same activity to allow a multi-pane UI with several fragments responsible for different screen sections.
Lifecycle:
Fragments have their own lifecycle, similar to activities, with methods like onCreate, onStart, onResume, and so on.
They are typically hosted within an activity, and their lifecycle is tied to the hosting activity.
UI Components:
Fragments can have their own UI components defined using XML layout files.
They can include elements like buttons, text fields, and more.
Fragment Transactions:
Fragments are added, replaced, or removed dynamically through fragment transactions.
Fragment transactions are managed by the FragmentManager and are used to change the content of an activity dynamically.
Communication Between Fragments:
Fragments can communicate with each other and with their hosting activity.
Communication can be achieved using interfaces or through the FragmentManager when fragments are hosted by the same activity.
Back Stack:
Fragment transactions can also be provided with back stack if required which makes the fragment similar to the back stack activity.
Dynamic UI:
In this case, fragments are useful when working with responsiveness in context with UI, particularly when the chosen layout should be suitable for different screen sizes and orientations.
Here's a simple example of using a fragment:
public class MyFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_layout, container, false);
}
// Other fragment-specific methods can be overridden as needed
}