Chapter 8. Fragments

In Android 3.0 (API Level 11), Android introduced the Fragments API. This was in response to a growing need to accommodate multiple screen sizes (such as tablets versus phones) and orientations (landscape versus portrait). To do this, it was necessary to modularize the views (the UI) such that it would be easy to separate the Activity container from the UI. This enables the developer to create a more responsive and easy-to-build interface to the user’s needs—such as changing the interface on the fly rather than having to create completely new containers for every configuration.

Fragment Example

To show how easy it is to convert an activity into a fragment, let’s start with the StatusActivity we created in a previous chapter. For reference, Example 8-1 is a copy of the old file and Example 8-2 is a copy of the layout XML (the activity_status.xml file) for StatusActivity.

Example 8-1. Old StatusActivity

import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import ...

Get Learning Android, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.