Fragment is a modular approach to design the User interface for the android based application. Fragment concept is introduced in android 3.0 (API level 11). Fragment gives the liberty to user for designing layouts which supports mobile as well as tablet version of the application.
Through this blog I would like to share some of the fundamentals and working of the fragment and how can we achieve the scalable interface with fragment.
Fragment gives immense opportunity to User interface designer to get the fill of mobile and tablet. Fragment runs with the activity which started it and it has its own life cycle as activity has the only difference with life cycle of fragment is it is managed by the activity which hosted the fragment. In the case of activity the life cycle is managed by android system. You can consider the fragment as sub-activity of the activity which runs in its own world managed by host activity. Fragment’s life cycle is affected by the life cycle of the host activity. As the activity pause the fragment pauses and if activity destroys the fragment destroys.
Fragment lives in the ViewGroup when you add them in the activity and stays there till activity lives.
Above image shows the behavior of the fragment on tablet and mobile device. the UI is automatically get adjusted according to device.
- XML : <fragment> tag is use to add the fragment in the xml file of the android application
- By code: FragmentManager api is used to add the fragment into your application. Which is followed by add, update and delete of the fragment.
Type of Fragment
- DiglogFragment: Used to show floating dialog in the activity. Why this is difference from conventional dialog api is that it maintains the stack of the dialog show so application can have stack of the displayed dialog and user can get back the previously shown dialog.
- ListFragment: Displays list of items which are managed by the adapter and it provides several methods to mange that li
- PreferenceFragment: Displays list of nested preference objects as similar to preference Activity. This is useful when creating the settings activity for the application.
- Add() : adds a fragment to the back stack and shows to the user
- Remove() : removes particular fragment from the back stack and manages other fragment accordingly
- Replace (): replace the existing fragment with new one.
- Commit() : the important call to perform all the above transaction
When to use fragment?
- When your application need to support portrait as well as landscape mode
- Applications designs have multi pan content
- Application needs to support mobile as well as tablets
- Re-usability of the UI components
Life Cycle comparison with Activity (Important)
Above image clearly state the fragment’s life cycle method in line with Activities methods so developers needs to keep this things handy while developing for the fragments.
For more details: http://developer.android.com/guide/components/fragments.html