How-To: Android Fragments

Typically, an Android user interface is composed of views within layouts, such as a ListView within a LinearLayout. A hierarchy of View objects gets loaded or created when an Activity is started. On small screens, this is fine.
But when you spread a UI out over the surface of a tablet’s screen, it calls for a different style of interaction. Some parts of the screen should remain constant over longer durations than others

While developers can implement interactions where parts of the screen change by showing and hiding views, Android’s developers decided they needed more than just convention to encourage better large screen UIs and consistent implementation of the feel of the UI. Now, in order to facilitate this new kind of interaction, as part of the Android 3.0 SDK, we get a class called Fragment.

A Fragment object is something between a View and and Activity: It can be part of a layout, but it isn’t a subclass of View.
It implements the ComponentCallbacks interface, and it has a lifecycle, but that lifecycle is dependent on the Activity the Fragment object belongs to.
Let’s see what it can do in a tablet-sized user interface.

Here are the contents of the main.xml file that describes a screen layout for our application. In a list on the left of the screen some numbers will appear. Selecting a number from that list will create that many Android icons, displayed in a Fragment instance on the right.

<!--?xml version="1.0" encoding="utf-8"?-->
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/frags">

android:id="@+id/number_list"
android:layout_width="250dip"
android:layout_height="match_parent" />

android:id="@+id/the_frag"
android:layout_width="match_parent"
android:layout_height="match_parent" />

The code for the Fragment subclass referred to in the layout in main.xml is below.

package com.my;

import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class FragmentExample extends Fragment {
private int nAndroids;

public FragmentExample() {
}

/**
* Constructor for being created explicitly
*/

public FragmentExample(int nAndroids) {
this.nAndroids = nAndroids;
}

/**
* If we are being created with saved state, restore our state
*/

@Override
public void onCreate(Bundle saved) {
super.onCreate(saved);
if (null != saved) {
nAndroids = saved.getInt("nAndroids");
}
}

/**
* Save the number of Androids to be displayed
*/

@Override
public void onSaveInstanceState(Bundle toSave) {
toSave.putInt("nAndroids", nAndroids);
}

/**
* Make a grid and fill it with n Androids
*/

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saved) {
int n;
Context c = getActivity().getApplicationContext();
LinearLayout l = new LinearLayout(c);
for (n = 0; n < nAndroids; n++) {
ImageView i = new ImageView(c);
i.setImageResource(R.drawable.android);
l.addView(i);
}
return l;
}
}
package com.my;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class FragmentExampleActivity extends Activity implements
OnItemClickListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

ListView l = (ListView) findViewById(R.id.number_list);
ArrayAdapter numbers = new ArrayAdapter(
getApplicationContext(), android.R.layout.simple_list_item_1,
new String[] { "one", "two", "three", "four", "five", "six" });
l.setAdapter(numbers);
l.setOnItemClickListener(this);
}

/**
* Add a Fragment to our stack with n Androids in it
*/

private void stackAFragment(int nAndroids) {
Fragment f = new FragmentExample(nAndroids);

FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.the_frag, f);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
}

/**
* Called when a number gets clicked
*/

public void onItemClick(AdapterView<!--?--> parent, View view, int position, long id) {
stackAFragment(position + 1);
}
}

This is what you see when you when you run the program: Initially, you see a list of numbers, and a blank area to the right.

Touch a number, and a new Fragment is created, with the specified number of Android icons. If you keep touching numbers in the list on the left, the corresponding number of Android icons appears in the Fragment instance on the right. Now try the back button. Instead of returning to an instance of the Activity that was on the screen before this application launched, you see the previous Fragment instance on the right. That is, the Fragment objects have been integrated into the task’s back stack.

Fragments are a new feature of Android, and this brief example only scratches the surface of how Fragment will change the way Android UIs are implemented. You can see from this example that using Fragments is efficient and expressive.
You can read more about Fragment, and how it can be used alongside starting Activity objects to drill into detail views in an Android UI in an article by Dianne Hackborn, here.

Download source code FragmentExample [19kB]

  1. Paresh
    The article is awesome and i have referred this article to develop my first screen. Thanx But, Please Let me know one thing: What if i want to Inflate the layout inside the onCreateView method of Fragments: For example, @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saved) { // Inflate the layout for this fragment mContentView = inflater.inflate(R.layout.mainactivitylist, null); final TextView txtViewTitle = (TextView) mContentView.findViewById(R.id.txtViewTitle); txtViewTitle.setText(itemTitle); return mContentView; } If i write this then TextView is already visible first time (Actually, i am displaying value inside this textview based on the listview item click shown on left-side). When i click on any item from a listview, then again new TextView (1st textview is already there) is added with value displayed. What should i do to dont display initial textview ? I just want to display textview based on the Listview item click?
  2. Lilu
    hello, thanks for the tutorial, do not speak English, so if I can not understand, I ask for your help, I want to create a list q to señeccionar an item from the list displays a default text me, if I select another item from another text display setting. I would appreciate help me, as a change in your tutorial q pictures but I leave a text? would believe that change is here, in the FragmentExample.java public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saved) { int n; Context c = getActivity().getApplicationContext(); LinearLayout l = new LinearLayout(c); for (n = 0; n < nAndroids; n++) { ImageView i = new ImageView(c); i.setImageResource(R.drawable.android); l.addView(i); } return l; } but I don`t know how to save a different text to display, I saw somewhere that was saved in a text string you want, it then, but not how to do that: (
  3. sandy
    thanx nice example of fragment :) keep posting !!!

Leave a Reply

*

captcha *