O'Reilly logo

Learning Android, 2nd Edition by Masumi Nakamura, Marko Gargenta

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 StatusActivity.java file and Example 8-2 is a copy of the layout XML (the activity_status.xml file) for StatusActivity.

Example 8-1. Old StatusActivity
package com.marakana.android.yamba;

import android.app.Activity;
import android.graphics.Color;
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 com.marakana.android.yamba.clientlib.YambaClient;
import com.marakana.android.yamba.clientlib.YambaClientException ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required