Table of Contents

Android - Fragment (with or without UI)

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:

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.

Example

Parent-Child View

Android - Parent-Child

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.

Android Tablet Handset Design

See also: responsive design

Management

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:

See guide/components/fragments.html

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 guide/components/fragments.html

Without UI

for the background, where you can keep up any:

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
    }

}

Finding a fragment

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

Documentation / Reference