Difference between revisions of "An Android Master/Detail Flow Tutorial"

From Techotopia
Jump to: navigation, search
Line 1: Line 1:
 
<table border="0" cellspacing="0" width="100%">
 
<table border="0" cellspacing="0" width="100%">
 
<tr>
 
<tr>
<td width="20%">[[Using Fragments in Android - A Worked Example|Previous]]<td align="center">[[Android 4 App Development Essentials|Table of Contents]]<td width="20%" align="right">[[Next]]</td>
+
<td width="20%">[[Using Fragments in Android - A Worked Example|Previous]]<td align="center">[[Android 4 App Development Essentials|Table of Contents]]<td width="20%" align="right">[[Creating and Managing Overflow Menus on Android|Next]]</td>
 
<tr>
 
<tr>
 
<td width="20%">Using Fragments in Android - A Worked Example<td align="center"><td width="20%" align="right">Creating and Managing Overflow Menus on Android</td>
 
<td width="20%">Using Fragments in Android - A Worked Example<td align="center"><td width="20%" align="right">Creating and Managing Overflow Menus on Android</td>

Revision as of 20:00, 26 June 2013

PreviousTable of ContentsNext
Using Fragments in Android - A Worked ExampleCreating and Managing Overflow Menus on Android


<google>BUY_ANDROID</google>


A clear understanding of how to use fragments (as outlined in the preceding chapters) is essential in order to be able to make use of the Master/Detail Flow template. This chapter will apply these skills to explain the concept of the Master/Detail user interface design before exploring in detail the elements that make up the Master/Detail Flow template included with the Android ADT bundle. Finally, an example application will be created that demonstrates the steps involved in modifying the template to meet the specific needs of the application developer.


Contents


The Master/Detail Flow

A master/detail flow is a interface design concept whereby a list of items (referred to as the master list) is displayed to the user. On selecting an item from the list, additional information relating to that item is then presented to the user within a details panel. An email application might, for example, consist of a master list of received messages consisting of the address of the sender and the subject of the message. Upon selection of a message from the master list, the body of the email message would appear within the detail panel.

On tablet sized Android device displays, the master list appears in a narrow vertical panel along the left hand edge of the screen. The remainder of the display is devoted to the detail panel in an arrangement referred to as two-pane mode. Figure 23-1, for example, shows the master/detail two-pane arrangement with three master items listed and the content of item three listed in the detail panel:


A two-pane Master/Detail Flow UI

Figure 23-1


On smaller, phone sized Android devices, the master list takes up the entire screen and the detail panel appears on a separate screen which appears when a selection is made from the master list. In this mode, the detail screen includes an action bar entry to return to the master list. Figure 23-2, for example, illustrates both the master and detail screens for the same three item list on a 4” phone screen:


A Master/Detail Flow UI on a small screen

Figure 23-2


Creating a Master/Detail Flow Activity

In the next section of this chapter, the different elements that comprise the Master/Detail Flow template will be covered in some detail. This is best achieved by creating a project using the Master/Detail Flow template to use while working through the information. This project will subsequently be used as the basis for the tutorial at the end of the chapter.

Begin by launching Eclipse and selecting the File -> New -> Android Application menu option. Enter MasterDetailFlow as both the application and project name and specify a suitable package name (or com.example.masterdetailflow as a placeholder if you do not have a company URL).

Select the latest SDK for each of the SDK menu options (at time of writing this is Android 4.2) before clicking the Next button. Click Next to accept the defaults on the Configure Project and Configure Launcher Icon screens.

When the Create Activty screen appears select the Master/Detail Flow option as illustrated in Figure 23-3 before clicking on Next once again:


Selecting the Master/Detail Flow Activity template

Figure 23-3


The next screen (Figure 23-4), entitled Master/Detail Flow, provides the opportunity to configure the objects that will be displayed within the master/detail activity. In the tutorial later in this chapter, the master list will contain a number of web site names which, when selected, will load the selected web site into a web view within the detail panel. With these requirements in mind, set the Object Kind field to “Website” and the Object Kind Plural setting to “Websites”.


Configuring the object kind information for a Master/Detail Flow project

Figure 23-4


Finally, click finish to create the new Master/Detail Flow based application project.


The Anatomy of the Master/Detail Flow Template

Once a new project has been created using the Master/Detail Flow template, a number of Java and XML layout resource files will have been created automatically. It is important to gain an understanding of these different files in order to be able to adapt the template to specific requirements. A review of the project within the Eclipse Package Explorer panel will reveal the following files, where <kind_name> is replaced by the Object Kind name that was specified when the project was created (this being “Website” in the case of the MasterDetailFlow example project):

  • <kind_name>ListActivity.java – This is the main activity of the project, the purpose of which is to display the master list to the user (the layout for which is stored in the activity_<kind_name>_list.xml XML Fragment resource file). If the class detects that the display is large enough to support two-pane mode, an instance of the <kind_name>_list fragment from the activity_<kind_name>_twopane.xml file is created and displayed, otherwise, the instance contained in the activity_<kind_name>_list.xml file is used. This class also implements and sets up the onItemSelected() callback method that will be called when the user makes a selection from the master list. It is the responsibility of this method to create and display an instance of the detail panel. In the case of two-pane mode, the detail panel is handled by creating an instance of the <kind_name>DetailFragment class and adding it to the current activity. On smaller device displays, this instead involves launching a second activity in the form of the <kind_name>DetailActivity class (which will then, in turn, create an instance of the <kind_name>DetailFragment class).
  • activity_<kind_name>_twopane.xml – Contains both the <kind_name>_list master list fragment and <kind_name>_detail_container FrameLayout declarations for the detail pane to be used when the application is running on a device large enough to support two-pane mode.
  • activity_<kind_name>_list.xml – The XML layout resource file containing the <kind_name>_list fragment for the master list to be used on displays too small to support two-pane mode.
  • <kind_name>ListFragment.java – The Java class that accompanies the activity_<kind_name>_list.xml fragment resource file. This class contains a number of methods that serve to identify and highlight the user’s current master list selection.
  • <kind_name>DetailActivity.java – The Java class representing the activity for the detail panel for use on devices too small to handle two-pane mode. This class creates an instance of the <kind_name>FragmentDetail class and displays the <kind_name>_detail_container FrameLayout container declared in the activity_<kind_name>_detail.xml file.
  • activity_<kind_name>_detail.xml – The XML resource layout that accompanies the <kind_name>ActivityDetail.java class file used on small screen devices. By default, this contains a FrameLayout instance to which will be added user interface elements declared by the <kind_name>FragmentDetail class.
  • <kind_name>DetailFragment.java – The Java class that accompanies the fragment_<kind_name>_detail.xml XML resource file. The code in this method loads the data associated with the master list and displays the content of the fragment_<kind_name>_detail.xml file to the user.
  • fragment_<kind_name>_detail.xml – The <kind_name>_detail user interface for the detail pane that is displayed within the onCreateView() method of the <kind_name>DetailFragment class. By default, this contains a single TextView object instance and is used in both two-pane and small screen modes.
  • DummyContent.java – A class file intended to provide sample data for the template. This class can either be modified to meet application needs, or replaced entirely. By default, the content provided by this class simply consists of a number of string items.

Two additional files are also of interest purely for the sake of understanding how the application is able to identify whether to use two-pane mode or not. These files are res/values-large/refs.xml and res/values-sw600dp/refs.xml.

As will be outlined in greater detail in the chapter entitled Handling Different Android Devices and Displays, each application project has multiple sets of resources that target different display sizes. At runtime, the Android system automatically uses the resource set that most closely matches the physical display size of the device. The values-large and values-sw600dp resources are, of course, used in devices with larger displays. The ref.xml files in these folders simply declare an alias that causes the two-pane mode layouts to be used:

<item name="activity_item_list" type="layout">@layout/activity_item_twopane</item>

Modifying the Master/Detail Flow Template

Whilst the structure of the Master/Detail Flow template can appear confusing at first, the concepts will become clearer as the default template is modified in the remainder of this chapter. As will become evident, much of the functionality provided by the template can remain unchanged for many master/detail implementation requirements.

In the rest of this chapter, the MasterDetailFlow project will be modified such that the master list displays a list of web site names and the detail pane altered to contain a WebView object instead of the current TextView. When a web site is selected by the user, the corresponding web page will subsequently load and display in the detail pane.

Changing the Content Model

The content for the example as it currently stands is defined by the DummyContent class file. Begin, therefore, by selecting the DummyContent.java file and reviewing the code. At the bottom of the file is a declaration for a class named DummyItem which is currently able to store two String objects representing a content string and an ID. The updated project, on the other hand, will need each item object to contain an ID string, a string for the web site name, and a string for the corresponding URL of the web site. To add these features, modify the DummyItem class so that it reads as follows:

public static class DummyItem {
	public String id;
	public String website_name;
	public String website_url;

	public DummyItem(String id, String website_name, 
             String website_url) 
	{
		this.id = id;
		this.website_name = website_name;
		this.website_url = website_url;
	}
	
	@Override
	public String toString() {
		return website_name;
	}
}

Note that the class currently adds three items in the form of strings that read “Item 1”, “Item 2” and “Item 3”:

public static Map<String, DummyItem> ITEM_MAP = 
          new HashMap<String, DummyItem>();

static {
	// Add 3 sample items.
	addItem(new DummyItem("1", "Item 1"));
	addItem(new DummyItem("2", "Item 2"));
	addItem(new DummyItem("3", "Item 3"));
}

This code needs to be modified to initialize the data model with the required web site data:

public static Map<String, DummyItem> ITEM_MAP = 
          new HashMap<String, DummyItem>();

static {
	// Add 3 sample items.
	addItem(new DummyItem("1", "eBookFrenzy", 
		"http://www.ebookfrenzy.com"));
	addItem(new DummyItem("2", "Google", 
		"http://www.google.com"));
	addItem(new DummyItem("3", "Android", 
		"http://www.android.com"));
}

The code now takes advantage of the modified DummyItem class to store an ID, web site name and URL for each item.

Changing the Detail Pane

The detail information shown to the user when an item is selected from the master list is currently displayed via the layout contained in the fragment_website_detail.xml file. By default this contains a single view in form of a TextView. Since the TextView class is not capable of displaying a web page, this needs to be changed to a WebView object for the purposes of this tutorial. To achieve this, navigate to the res -> layout -> fragment_website_detail.xml file in the Project Explorer panel and double click on it to load it. Switch to the Graphical Layout tool display if it is not already displayed before right-clicking on the white background of the display canvas (which represents the TextView). From the resulting menu, select the Change Widget Type… menu option. In the Change Widget Type dialog, change the widget type from TextView to WebView before clicking on OK to commit the change.

Modifying the WebsiteDetailFragment Class

At this point the user interface detail panel has been modified but the corresponding Java class is still designed for working with a TextView object instead of a WebView. Load the source code for this class by double clicking on the WebsiteDetailFragment.java file in the Project Explorer panel. Within the source file locate the onCreateView() method which should read as outlined in the following listing:

package com.example.masterdetailflow;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
.
.
.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
		Bundle savedInstanceState) {

	View rootView = 
		inflater.inflate(R.layout.fragment_website_detail,
			container, false);

	// Show the dummy content as text in a TextView.
	if (mItem != null) {
		((TextView) rootView.findViewById(R.id.website_detail))
				.setText(mItem.content);
	}

	return rootView;
}

In order to load the web page URL corresponding to the currently selected item only one line of code needs to be changed. Once this change has been made, the method should read as follows (note also the addition of the import directive for the android.webkit.WebView library):

package com.example.masterdetailflow;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
.
.
.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
		Bundle savedInstanceState) {

	View rootView = 
		inflater.inflate(R.layout.fragment_website_detail,
			container, false);

	// Show the dummy content as text in a TextView.
	if (mItem != null) {
		((WebView) rootView.findViewById(R.id.website_detail))
			.loadUrl(mItem.website_url);
	return rootView;
}

All that this change does is find the view with the ID of website_detail (this was formally the TextView but is now a WebView), extracts the URL of the web site from the selected item and instructs the WebView object to load that page.

Adding Manifest Permissions

The final step is to add internet permission to the application via the manifest file. This will enable the WebView object to access the internet and download web pages. Navigate to and load the AndroidManifest.xml file in the Project Explorer panel and double click on it to load it into the Manifest Editor. Click on the AndroidManifest.xml tab along the bottom edge of the editor panel to directly access the XML and add the appropriate permission line to the file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.masterdetailflow"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-permission android:name="android.permission.INTERNET" />"
    
    <uses-sdk
        android:minSdkVersion="17"
        android:targetSdkVersion="17" />
.
.
.
</manifest>

Running the Application

Compile and run the application on a suitably configured emulator or an attached Android device. Depending on the size of the display, the application will appear either in small screen or two-pane mode. Regardless, the master list should appear primed with the names of the three web sites defined in the content model. Selecting an item should cause the corresponding web site to appear in the detail panel as illustrated in two-pane mode in Figure 23-5:


An Android Master/Detail example running in two-pane mode

Figure 23-5


Summary

A master/detail user interface consists of a master list of items which, when selected, displays additional information about that selection within a detail panel. The Master/Detail Flow is a template provided with the Android ADT bundle that allows a master/detail arrangement to be created quickly and with relative ease. As demonstrated in this chapter, with minor modifications to the default template files, a wide range of master/detail based functionality can be implemented with minimal coding and design effort.


<google>BUY_ANDROID</google>



PreviousTable of ContentsNext
Using Fragments in Android - A Worked ExampleCreating and Managing Overflow Menus on Android