Android - Fragment (with or without UI)

> Android

1 - About

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.

Advertising

3 - Example

3.1 - Parent-Child View

3.2 - Multi-pane UI

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

3.3 - Responsive Design (Screen Size)

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

See also: responsive design

4 - Management

4.1 - 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#Creating

Advertising

4.2 - 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#UI

4.3 - Without UI

for the background, where you can keep up any:

  • connection
  • or threads
public class NonUIFragment extends Fragment {
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true); // Must be set to true
    }
 
    @Override
    public View onCreateView(...) {
        return null; // You need to return null
    }
 
}

4.4 - Finding a fragment

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

5 - Documentation / Reference

Advertising