Fragment is sort of like a “sub activity” that you can reuse in different activities.
It can:
have its own lifecycle
receive its own input events
add or remove while the activity is running
To use fragment, it needs at least Support Library v4. But better to use v7 which is compatible with Android 2.1 (API level 7) and also includes the Fragment APIs.
For activity, it needs to extend AppCompatActivity when with v7. In fact, FragmentActivity is a special activity provided in Support Library to handle fragments on system versions older than API level 11. If the lowest system version is API level 11 or higher, then we can use a regular Activity. As here AppCompatActivity is a subclass of FragmentActivity and it could support older versions. So just use it :D
Steps to use fragment:
Add Support Library.
Define fragment layout xml
Create fragment class
Add fragment to activity statically/dynamically
Define Fragment Layout
Its layout has no difference with activity’s:
Create Fragment Class
Like onCreate() in Activity, fragment uses onCreateView() callback to define the layout. It is the only callback we need in order to get a fragment running.
Add Fragment to Activity
There are two ways:
Statically by <fragment>
Dynamically by <FrameLayout> and FragmentManager
Statically
Add each fragment in activity layout XML file:
Dynamically
Dynamically means adding a fragment to an activity at Runtime instead of defining fragments in activity layout file.
Add firstly in activity’s layout includes an empty <FrameLayout> that acts as the fragment container:
Add initial fragment(s) to activity in onCreate() by FragmentTransaction:
FragmentTransaction here is to provides APIs to add, remove, replace, and perform other fragment transactions.
To replace fragment:
When replace/remove fragments, it needs to allow user to navigate backward and “undo” the change. It is why transaction.addToBackStack(null) is called here before commit. It makes fragment to be stopped instead of destroyed when we replace/remove it.
What’s more, this method takes an optional string parameter that specifies a unique name for the transaction. The name isn’t needed unless we plan to perform advanced fragment operations using FragmentManager.BackStackEntry APIs.