Creating Android fragments

Creating Android fragments is a reusable class implementing a portion of an activity. A Fragment typically defines a part of a user interface. Fragments must be embedded in activities; they cannot run independently of activities.

A fragment has a separate layout XML file. A Fragment encapsulates functionality so that it is easier to reuse within activity and layouts.

Fragments can be dynamically (Java) or statically (XML) added to an activity layout.

Defining a Fragment

Creating a fragment, like an activity, has an XML layout file and a Java class that represents the Fragment controller.

The XML layout file is just like any other layout file, and can be named fragment_foo.xml. Think of them as a partial (re-usable) activity:

The Java controller for a fragment looks like:

Embedding a Fragment in an Activity

There are two ways to add a fragment to an activity: dynamically using Java and statically using XML.

Before embedding a “support” fragment in an Activity make sure the Activity is changed to extend from FragmentActivitywhich adds support for the fragment manager to all Android versions. Any activity using fragments should make sure to extend from FragmentActivity:


To add the fragment statically, simply embed the fragment in the activity’s xml layout file:


The second way is by adding the fragment dynamically in Java using the FragmentManager. The FragmentManager class and the FragmentTransaction class allow you to add, remove and replace fragments in the layout of your activity.

In this case, you need a “placeholder” FrameLayout that can later be replaced with the fragment:

and then you can use the FragmentManager to create a FragmentTransaction which allows us to replace the FrameLayout with any fragment at runtime:

If the fragment should always be in the activity, use XML to statically add but if it’s more complex use the Java-based approach.

Fragment Lifecycle

Fragment has many methods which can be overridden to plug into the lifecycle (similar to an Activity):

  • onAttach() is called when a fragment is connected to an activity.
  • onCreate() is called to do initial creation of the fragment.
  • onCreateView() is called by Android once the Fragment should inflate a view.
  • onActivityCreated() is called when host activity has completed its onCreate() method.
  • onStart() is called once the fragment gets visible.
  • onResume() – Allocate “expensive” resources such as registering for location, sensor updates, etc.
  • onPause() – Release “expensive” resources. Commit any changes.
  • onDestroyView() is called when fragment’s view is being destroyed, but the fragment is still kept around.
  • onDestroy() is called when fragment is no longer in use.
  • onDetach() is called when fragment is no longer connected to the activity.

The lifecycle execution order is mapped out below:

Creating Android fragments

The most common ones to override are onCreateView which is in almost every fragment to setup the inflated view, onCreatefor any data initialization and onActivityCreated used for setting up things that can only take place once the Activity has been fully created.

Here’s an example of how you might use the various fragment lifecycle events:

This chart has the lifecycle displayed visually.

Communicating with Fragments

Fragments should not directly communicate with each other, only through an activity. Fragments should be modular and reusable components. Let the activity respond to intents and fragment callbacks in most cases.

There are three ways a fragment and an activity can communicate:

  1. Activity can construct a fragment and set arguments
  2. Activity can call methods on a fragment instance
  3. Fragment can fire listener events on an activity via an interface

Fragment with Arguments

In certain cases, your fragment may want to accept certain arguments. A common pattern is to create a static newInstancemethod for creating a Fragment with arguments. This is because a Fragment must have only a constructor with no arguments. Instead, we want to use the setArguments method such as:

This sets certain arguments into the Fragment for later access within onCreate. You can access the arguments later by using:

Now we can load a fragment dynamically in an Activity with:

This pattern makes passing arguments to fragments for initialization fairly straightforward.

Fragment Methods

If an activity needs to make a fragment perform an action after initialization, the easiest way is by having the activity invoke a method on the fragment instance. In the fragment, add a method:

and then in the activity, get access to the fragment using the fragment manager and call the method:

and then the activity can communicate directly with the fragment by invoking this method.

Fragment Listener

If a fragment needs to communicate events to the activity, the fragment should define an interface as an inner type and require that the activity must implement this interface:

and then in the activity:

in order to keep the fragment as re-usable as possible.

ActionBar Menu Items and Fragments

One common case is the need for fragment-specific menu items that only show up for that fragment. This can be done by adding an onCreateOptionsMenu method to the fragment directly. This works just like the one for the activity:

You then also need to notify the fragment that it’s menu items should be loaded within the fragment’s onCreate method:

Clicks can be handled using onClick property as usual or more typically in this case, using the onOptionsItemSelected method in the fragment:

Note that the fragment’s method is called only when the Activity didn’t consume the event first.

Navigating Between Fragments

There are several methods for navigating between different fragments within a single Activity. The primary options are:

  1. ActionBar Tabs – Tabs at the top
  2. Fragment Navigation Drawer – Slide out navigation menu
  3. ViewPager – Swiping between fragments

Managing Fragment Backstack

A record of all Fragment transactions is kept for each Activity by the FragmentManager. When used properly, this allows the user to hit the device’s back button to remove previously added Fragments (not unlike how the back button removes an Activity). Simply call addToBackstack on each FragmentTransaction that should be recorded:

Programmatically, you can also pop from the back stack at any time through the manager:

With this approach, we can easily keep the history of which fragments have appeared dynamically on screen and allow the user to easily navigate to previous fragments.

Fragment Hiding vs Replace

In many of the examples above, we call transaction.replace(...) to load a dynamic fragment which first removes the existing fragment from the activity invoking onStop and onDestroy for that fragment before adding the new fragment to the container. This can be good because this will release memory and make the UI snappier. However, in many cases, we may want to keep both fragments around in the container and simply toggle their visibility. This allows all fragments to maintain their state because they are never removed from the container. To do this, we might modify this code:

to this approach instead leveraging add, show, and hide in the FragmentTransaction:

Using this approach, all three fragments will remain in the container once added initially and then we are simply revealing the desired fragment and hiding the others within the container.