Android - Fragment (with or without UI)


Fragment is sort of like a “sub Activity” that you can reuse in different activities.

Each fragment should be designed as a modular and reusable activity component because each fragment defines:

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.

When you add a fragment in an activity, it lives in a ViewGroup inside the activity's view hierarchy and the fragment defines its own view layout. You can insert a fragment into your activity layout by:

  • declaring the fragment in the activity's layout file, as a <fragment> element,
  • or by adding it from your application code to an existing ViewGroup.

However, a fragment is not required to be a part of the activity layout; you may also use a fragment without its own UI as an invisible worker for the activity.


Parent-Child View

Multi-pane UI

You can combine multiple fragments in a single activity to build a multi-pane UI.

Responsive Design (Screen Size)

A modular fragment allows you to change your fragment combinations for different screen sizes.

See also: responsive design


Creating a Fragment

To create a fragment, you must create a subclass of Fragment (or an existing subclass of it). The Fragment class has code that looks a lot like an Activity. It contains callback methods similar to an activity, such as:

  • onCreate(),
  • onStart(),
  • onPause(), where: commit any changes that should be persisted beyond the current user session (because the user might not come back).
  • and onStop().

See components/fragments

Adding a layout

To provide a layout for a fragment, you must implement the onCreateView() callback method, which the Android system calls when it's time for the fragment to draw its layout. Your implementation of this method must return a View that is the root of your fragment's layout.

See components/fragments

Without UI

for the background, where you can keep up any:

  • connection
  • or threads
public class NonUIFragment extends Fragment {

    public void onCreate(Bundle savedInstanceState) {
        setRetainInstance(true); // Must be set to true
    public View onCreateView(...) {
        return null; // You need to return null


Finding a fragment

  • by Id
MyFragment myfr = (myFragment) getSupportManager().findFragmentById(;
  • by Tag
MyFragment myfr = (myFragment) getSupportManager().findFragmentByTag("TheBeautifulTag");

Documentation / Reference

Powered by ComboStrap