Dynamic layouts using fragments

  • Written by  Clive

Fragments: What you should know

Seriously, what are fragments?

fragments iconThink of components like buttons and images. You can reuse them over and over in different activities. You can also rearrange them within an activity.

Fragments are similar.

Fragments let you divide your activity into reusable components which have their own User Interface and lifecycle.

You can then use these fragments in a flexible way. Adding them to and removing them from your activities while they run.

Fragments allow you to offer a consistent UI across different devices with different screen sizes and densities.

Each fragment is an independent module but must be bound to an activity else it does not exist.

Fragments don’t have to have a User interface. You can also use them as invisible workers for activities, doing the work behind the scenes.

Fragments diagram

Fragments present a consistent User Interface across different devices and screen sizes. Top left is an example of a mobile phone using fragments. Top right is a tablet and at the bottom is a mobile phone in landscape mode

Which version of Android do I need for fragments?

Fragments have been around since Android 3.0 (API Level 11).

You can also use them from Android 1.6 (API Level 4) thanks to the support library.

If you use the support library, make sure that you import the support class and use its methods throughout the app.

The cycle of life: The Fragment lifecycle

The fragment’s lifecycle events mirror those of its parent activity.

Have a look at the article The Activity Lifecycle for more on this.

The Fragment lifecycle diagram

The fragment lifecycle

Fragment specific lifecycle events

Fragments have a number of unique event handlers.

Handlers for attaching and detaching fragments

The fragment’s full lifecycle begins when it attaches to its parent activity. It ends when it has detached.

onAttach is called when the fragment is attached to its parent activity. This happens before the fragment’s User Interface has been created and before the fragment’s parent activity has finished initializing.

Use onAttach to get a reference to the parent activity which you can then use in later initialization tasks.

onDetach is called when the fragment has been detached from its parent activity.

Note that onDetach may never be called if the parent activity is killed without completing its full lifecycle.

Handlers for creating and destroying fragments

The created lifetime of a fragment stretches from onCreate until onDestroy.

onCreate is used to initialise the fragment. Create your class objects here. It’s called once in the lifetime of the fragment.

onDestroy can be used to release resources for use elsewhere.

Be aware that the fragment may be destroyed without onDestroy being called.

Handlers for creating and destroying the fragment’s UI

onCreateView is used to initialize the fragment. This is where you inflate the User Interface and get references to its views.

onDestroyView is called when the fragment’s view has been detached from its parent activity. Use it to release any resources used by the view.

Look at the state I’m in: Fragment states

Fragments can only exist when attached to an activity. Their state is therefore linked to the state of their parent activity.

Active state

Fragments are active when its parent activity is active. Similarly when a parent activity pauses or stops, then its embedded fragment also pauses or stops.

Inactive state

Fragments are inactive when their parent activities are inactive and destroyed when the parent activity is destroyed.

A fragment can move through its lifecycle a number of times within the active lifetime of its parent activity.

It’s important to manage these lifecycle transitions so as to ensure a seamless experience for the user.

Hire a manager

Use the Fragment Manager within the parent activity to manage the fragments that it contains.

The Fragment Manager has methods that you can use to access the currently embedded fragments.  

You can then add, replace and remove fragments while the activity is running.

Adding fragments to activities

There are two ways that you can add a fragment to an activity.

The static way

The easiest way to embed fragments in an activity is to define the fragments in the activity’s xml layout file.

The layout is then inflated in the activity and the fragment becomes a View Group, within the activity’s layout. The fragment manages its own User Interface within the activity.

This option is great for static layouts for various screen sizes.

The dynamic way

If you plan to dynamically modify layouts by adding, removing and replacing fragments while the activity is running then you should use container views in the activity’s layout.

Then at runtime, you create the fragments in the activity’s onCreate method and place them in the containers.

Ch…Ch...Changes: Fragment transactions

Use Fragment Transactions to add, replace and remove fragments inside the parent activity while it is running.

Fragment Transactions makes it easy to dynamically change your layout depending on the user’s interaction, the state of the app and the size and shape of the device.

Keeping up appearances: Persisting the Fragment’s Instance State

The system, by default takes care of saving the fragment's User Interface. Use the onSaveInstanceState method if you want to save any additional information.

The information is saved in a Bundle object. The bundle is passed to onCreate, onCreateView and onActivityCreated where you can extract the data and restore the fragment.

Have a look at this article, Persisting the Activity Instance State for more on saving the Instance State.

Turning back the clock: Fragments and the Backstack

When a user presses the Back button, they expect to return to the previous screen. Placing fragments on the Backstack makes this possible.

You have to request that a fragment be added to the Backstack. The stack is then managed by the parent activity.

Pressing the Back button reverses the previous transaction and returns the User Interface to the previous layout.

WhatsUp: activity and fragment communication

If your fragment needs to communicate with the parent activity, then it’s good practice that it has a callback interface. The host activity must then implement this interface.

Although fragments can communicate directly with each other, it’s best to use the activity as a go-between.

Fragments can access their parent activity using getActivity. It’s useful for getting the current context, accessing other fragments and finding views within the activity’s view hierarchy.

Have a look at the 3 part series of tutorials on using fragments in an app. Here's a link to part 1: The Basics.

Want to convert your Activities to Fragments? Check out this tutorial, Converting Android Activities to Fragments

I hope that you have found this tutorial helpful.