6 Fragments
6 Fragments
6 Fragments
A fragment must always be hosted in an activity and the fragment's lifecycle is directly
affected by the host activity's lifecycle. For example, when the activity is paused, so are all
fragments in it, and when the activity is destroyed, so are all fragments. However, while an
activity is running (it is in the resumed lifecycle state), you can manipulate each fragment
independently, such as add or remove them. When you perform such a fragment
transaction, you can also add it to a back stack that's managed by the activity—each back
stack entry in the activity is a record of the fragment transaction that occurred. The back
stack allows the user to reverse a fragment transaction (navigate backwards), by pressing
the Back button.
You can insert a fragment into your activity layout by declaring the fragment in the
activity's layout file, as a <fragment> element, or from your application code by adding it
to an existing ViewGroup(like FrameLayout).
Creating a Fragment
DialogFragment
ListFragment
PreferenceFragmentCompat
In this case, you can specify layout properties for the fragment as if it were a view.
For example, here's the layout file for an activity with two fragments:
When the system creates this activity layout, it instantiates each fragment specified
in the layout and calls the onCreateView() method for each one, to retrieve each
fragment's layout. The system inserts the View returned by the fragment directly
in place of the <fragment> element.
At any time while your activity is running, you can add fragments to your activity
layout. You simply need to specify a ViewGroup in which to place the fragment.
You can then add a fragment using the add() method, specifying the fragment to
add and the view in which to insert it. For example:
The first argument passed to add() is the ViewGroup in which the fragment should
be placed, specified by resource ID, and the second parameter is the fragment to
add.