Display Picture and Menu With Views
Display Picture and Menu With Views
Displaying Pictures
and Menus with Views
WHAT YOU WILL LEARN IN THIS CHAPTER
In the previous chapter, you learned about the various views that you can use to build the user
interface of your Android application. In this chapter, you continue your exploration of the
other views that you can use to create robust and compelling applications.
In particular, you will learn how to work with views that enable you to display images. In
addition, you will learn how to create option and context menus in your Android application.
This chapter ends with a discussion of some helpful views that enable users to display the
current time and web content.
www.it-ebooks.info
220 ❘ CHAPTER 5 DISPLAYING PICTURES AND MENUS WITH VIEWS
<TextView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Images of San Francisco” />
<Gallery
android:id=”@+id/gallery1”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content” />
<ImageView
android:id=”@+id/image1”
android:layout_width=”320dp”
android:layout_height=”250dp”
android:scaleType=”fitXY” />
</LinearLayout>
3. Right-click on the res/values folder and select New ➪ File. Name the fi le attrs.xml.
4. Populate the attrs.xml fi le as follows:
5. Prepare a series of images and name them pic1.png, pic2.png, and so on for each subsequent
image (see Figure 5-2).
www.it-ebooks.info
Using Image Views to Display Pictures ❘ 221
FIGURE 5-2
NOTE You can download the series of images from this book’s support website
at www.wrox.com.
6. Drag and drop all the images into the res/drawable-mdpi folder (see Figure 5-3). When a dialog
is displayed, check the Copy files option and click OK.
FIGURE 5-3
NOTE This example assumes that this project will be tested on an AVD with
medium DPI screen resolution. For a real-life project, you need to ensure that
each drawable folder has a set of images (of different resolutions).
www.it-ebooks.info
222 ❘ CHAPTER 5 DISPLAYING PICTURES AND MENUS WITH VIEWS
package net.learn2develop.Gallery;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;
gallery.setAdapter(new ImageAdapter(this));
gallery.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView parent, View v,
int position, long id)
{
Toast.makeText(getBaseContext(),
“pic” + (position + 1) + “ selected”,
Toast.LENGTH_SHORT).show();
}
});
}
www.it-ebooks.info
Using Image Views to Display Pictures ❘ 223
int itemBackground;
public ImageAdapter(Context c)
{
context = c;
//---setting the style---
TypedArray a = obtainStyledAttributes(
R.styleable.Gallery1);
itemBackground = a.getResourceId(
R.styleable.Gallery1_android_galleryItemBackground,
0);
a.recycle();
}
8. Press F11 to debug the application on the Android emulator. Figure 5-4 shows the Gallery view
displaying the series of images. You can swipe the images to view the entire series. Observe that as
you click on an image, the Toast class displays its name.
www.it-ebooks.info
224 ❘ CHAPTER 5 DISPLAYING PICTURES AND MENUS WITH VIEWS
FIGURE 5-4
9. To display the selected image in the ImageView, add the following statements in bold to the
GalleryActivity.java fi le:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gallery.setAdapter(new ImageAdapter(this));
gallery.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView parent, View v,
int position, long id)
{
Toast.makeText(getBaseContext(),
“pic” + (position + 1) + “ selected”,
Toast.LENGTH_SHORT).show();
10. Press F11 to debug the application again. This time, the image selected will be displayed in the
ImageView (see Figure 5-5).
www.it-ebooks.info
Using Image Views to Display Pictures ❘ 225
How It Works
You fi rst added the Gallery and ImageView views to main.xml:
<Gallery
android:id=”@+id/gallery1”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content” />
<ImageView
android:id=”@+id/image1”
android:layout_width=”320dp”
android:layout_height=”250dp”
android:scaleType=”fitXY” />
You create the ImageAdapter class (which extends the BaseAdapter class) so that it can bind to
the Gallery view with a series of ImageView views. The BaseAdapter class acts as a bridge between an
AdapterView and the data source that feeds data into it. Examples of AdapterViews are as follows:
➤ ListView
➤ GridView
➤ Spinner
➤ Gallery
➤ ArrayAdapter
➤ CursorAdapter
➤ SpinnerAdapter
www.it-ebooks.info
226 ❘ CHAPTER 5 DISPLAYING PICTURES AND MENUS WITH VIEWS
For the ImageAdapter class, you implemented the following methods in bold:
In particular, the getView() method returns a View at the specified position. In this case, you returned
an ImageView object.
When an image in the Gallery view is selected (i.e., clicked), the selected image’s position (0 for the
fi rst image, 1 for the second image, and so on) is displayed and the image is displayed in the ImageView:
gallery.setAdapter(new ImageAdapter(this));
gallery.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v,
int position, long id)
{
Toast.makeText(getBaseContext(),
“pic” + (position + 1) + “ selected”,
Toast.LENGTH_SHORT).show();
ImageSwitcher
The previous section demonstrated how to use the Gallery view together with an ImageView to
display a series of thumbnail images so that when one is selected, it is displayed in the ImageView.
However, sometimes you don’t want an image to appear abruptly when the user selects it in the
Gallery view — you might, for example, want to apply some animation to the image when it
www.it-ebooks.info
Using Image Views to Display Pictures ❘ 227
transitions from one image to another. In this case, you need to use the ImageSwitcher together
with the Gallery view. The following Try It Out shows you how.
<TextView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Images of San Francisco” />
<Gallery
android:id=”@+id/gallery1”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content” />
<ImageSwitcher
android:id=”@+id/switcher1”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:layout_alignParentLeft=”true”
android:layout_alignParentRight=”true”
android:layout_alignParentBottom=”true” />
</LinearLayout>
3. Right-click on the res/values folder and select New ➪ File. Name the fi le attrs.xml.
4. Populate the attrs.xml fi le as follows:
5. Drag and drop a series of images into the res/drawable-mdpi folder (refer to the previous
example for the images). When a dialog is displayed, check the Copy files option and click OK.
www.it-ebooks.info
228 ❘ CHAPTER 5 DISPLAYING PICTURES AND MENUS WITH VIEWS
package net.learn2develop.ImageSwitcher;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher.ViewFactory;
www.it-ebooks.info
Using Image Views to Display Pictures ❘ 229
}
});
}
public ImageAdapter(Context c)
{
context = c;
imageView.setImageResource(imageIDs[position]);
www.it-ebooks.info
230 ❘ CHAPTER 5 DISPLAYING PICTURES AND MENUS WITH VIEWS
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setLayoutParams(new Gallery.LayoutParams(150, 120));
imageView.setBackgroundResource(itemBackground);
return imageView;
}
}
How It Works
The fi rst thing to note in this example is that the
ImageSwitcherActivity not only extends Activity, but also
implements ViewFactory. To use the ImageSwitcher view, you need
to implement the ViewFactory interface, which creates the views for
use with the ImageSwitcher view. For this, you need to implement
the makeView() method:
This method creates a new View to be added in the ImageSwitcher view, which in this case is an
ImageView.
Like the Gallery example in the previous section, you also implemented an ImageAdapter class so that
it can bind to the Gallery view with a series of ImageView views.
In the onCreate() method, you get a reference to the ImageSwitcher view and set the animation,
specifying how images should “fade” in and out of the view. Finally, when an image is selected from the
Gallery view, the image is displayed in the ImageSwitcher view:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
www.it-ebooks.info
Using Image Views to Display Pictures ❘ 231
android.R.anim.fade_in));
imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_out));
In this example, when an image is selected in the Gallery view, it appears by “fading” in. When the
next image is selected, the current image fades out. If you want the image to slide in from the left and
slide out to the right when another image is selected, try the following animation:
imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.slide_in_left));
imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.slide_out_right));
GridView
The GridView shows items in a two-dimensional scrolling grid. You can use the GridView together
with an ImageView to display a series of images. The following Try It Out demonstrates how.
<GridView
android:id=”@+id/gridview”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
www.it-ebooks.info
232 ❘ CHAPTER 5 DISPLAYING PICTURES AND MENUS WITH VIEWS
android:numColumns=”auto_fit”
android:verticalSpacing=”10dp”
android:horizontalSpacing=”10dp”
android:columnWidth=”90dp”
android:stretchMode=”columnWidth”
android:gravity=”center” />
</LinearLayout>
package net.learn2develop.Grid;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
gridView.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView parent,
View v, int position, long id)
{
Toast.makeText(getBaseContext(),
“pic” + (position + 1) + “ selected”,
Toast.LENGTH_SHORT).show();
}
www.it-ebooks.info
Using Image Views to Display Pictures ❘ 233
});
public ImageAdapter(Context c)
{
context = c;
}
www.it-ebooks.info
234 ❘ CHAPTER 5 DISPLAYING PICTURES AND MENUS WITH VIEWS
How It Works
Like the Gallery and ImageSwitcher example, you implemented the ImageAdapter class and then
bound it to the GridView:
gridView.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView parent,
View v, int position, long id)
{
Toast.makeText(getBaseContext(),
“pic” + (position + 1) + “ selected”,
Toast.LENGTH_SHORT).show();
}
});
When an image is selected, you display a Toast message indicating the selected image.
Within the getView() method you can specify the size of the images and how images are spaced in the
GridView by setting the padding for each image:
www.it-ebooks.info
Using Menus with Views ❘ 235
package net.learn2develop.Menus;
import android.app.Activity;
www.it-ebooks.info
236 ❘ CHAPTER 5 DISPLAYING PICTURES AND MENUS WITH VIEWS
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
www.it-ebooks.info
Using Menus with Views ❘ 237
How It Works
The preceding example creates two methods: CreateMenu() and MenuChoice(). The CreateMenu()
method takes a Menu argument and adds a series of menu items to it.
To add a menu item to the menu, you create an instance of the MenuItem class and use the add()
method of the Menu object:
You can use the setAlphabeticShortcut() method to assign a shortcut key to the menu item so that
users can select an item by pressing a key on the keyboard. The setIcon() method sets an image to be
displayed on the menu item.
The MenuChoice() method takes a MenuItem argument and checks its ID to determine the menu item
that is selected. It then displays a Toast message to let the user know which menu item was selected.
www.it-ebooks.info
238 ❘ CHAPTER 5 DISPLAYING PICTURES AND MENUS WITH VIEWS
Options Menu
You are now ready to modify the application to display the options menu when the user presses the
MENU key on the Android device.
package net.learn2develop.Menus;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
CreateMenu(menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
return MenuChoice(item);
}
2. Press F11 to debug the application on the Android emulator. Figure 5-10 shows the options
menu that pops up when you click the MENU button. To select a menu item, either click on an
www.it-ebooks.info
Using Menus with Views ❘ 239
individual item or use its shortcut key (A to D; applicable only to the fi rst four items). Note that
menu items 1 to 3 did not display the icons even though the code explicitly did so.
3. If you now change the minimum SDK attribute of the AndroidManifest.xml fi le to a value of
10 or less and then rerun the application on the emulator, the icons will be displayed as shown
in Figure 5-11. Note that any menu items after the fi fth item are encapsulated in the item named
More. Clicking on More will reveal the rest of the menu items.
How It Works
To display the options menu for your activity, you need to implement two methods in your activity:
onCreateOptionsMenu() and onOptionsItemSelected(). The onCreateOptionsMenu() method is
called when the MENU button is pressed. In this case, you call the CreateMenu() helper method to
display the options menu. When a menu item is selected, the onOptionsItemSelected() method is
called. In this case, you call the MenuChoice() method to display the menu item selected (and perform
whatever action is appropriate).
Take note of the look and feel of the options menu in different versions of Android. Starting with
Honeycomb, the options menu items do not have icons and display all menu items in a scrollable list.
For versions of Android before Honeycomb, no more than five menu items are displayed; any additional
menu items are part of a “More” menu item that represents the rest of the menu items.
www.it-ebooks.info
240 ❘ CHAPTER 5 DISPLAYING PICTURES AND MENUS WITH VIEWS
Context Menu
The previous section showed how the options menu is displayed when the user presses the MENU
button. Besides the options menu, you can also display a context menu. A context menu is usually
associated with a view on an activity, and it is displayed when the user taps and holds an item. For
example, if the user taps on a Button view and holds it for a few seconds, a context menu can be
displayed.
If you want to associate a context menu with a view on an activity, you need to call the
setOnCreateContextMenuListener() method of that particular view. The following Try It Out
shows how you can associate a context menu with a Button view.
1. Using the same project from the previous example, add the following statements to the main.xml
fi le:
<?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:orientation=”vertical” >
<TextView
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”@string/hello” />
<Button
android:id=”@+id/button1”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:text=”Click and hold on it” />
</LinearLayout>
import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
www.it-ebooks.info
Using Menus with Views ❘ 241
import android.widget.Toast;
@Override
public void onCreateContextMenu(ContextMenu menu, View view,
ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, view, menuInfo);
CreateMenu(menu);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
//...
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
return MenuChoice(item);
}
www.it-ebooks.info
242 ❘ CHAPTER 5 DISPLAYING PICTURES AND MENUS WITH VIEWS
How It Works
In the preceding example, you call the
setOnCreateContextMenuListener() method of the Button view to
associate it with a context menu.
When the user taps and holds the Button view, the
onCreateContextMenu() method is called. In this method, you
call the CreateMenu() method to display the context menu.
Similarly, when an item inside the context menu is selected, the
onContextItemSelected() method is called, where you call the
MenuChoice() method to display a message to the user.
Notice that the shortcut keys for the menu items do not work.
To enable the shortcuts keys, you need to call the setQuertyMode()
method of the Menu object, like this:
FIGURE 5-12
private void CreateMenu(Menu menu)
{
menu.setQwertyMode(true);
MenuItem mnu1 = menu.add(0, 0, 0, “Item 1”);
{
mnu1.setAlphabeticShortcut(‘a’);
mnu1.setIcon(R.drawable.ic_launcher);
}
//...
}
www.it-ebooks.info
Some Additional Views ❘ 243
NOTE Creating your own custom views in Android is beyond the scope of this
book. However, if you are interested in this area, take a look at Google’s Android
documentation on this topic at http://developer.android.com/guide/
topics/ui/custom-components.html.
Using the AnalogClock and DigitalClock views are straightforward; simply declare them in your
XML fi le (such as main.xml), like this:
<AnalogClock
android:layout_width=”wrap_content”
android:layout_height=”wrap_content” />
<DigitalClock
android:layout_width=”wrap_content”
android:layout_height=”wrap_content” />
</LinearLayout>
WebView
The WebView enables you to embed a web browser in your activity.
This is very useful if your application needs to embed some web
content, such as maps from some other providers, and so on. The FIGURE 5-13
following Try It Out shows how you can programmatically load
the content of a web page and display it in your activity.
www.it-ebooks.info
244 ❘ CHAPTER 5 DISPLAYING PICTURES AND MENUS WITH VIEWS
android:layout_height=”fill_parent”
android:orientation=”vertical” >
<WebView android:id=”@+id/webview1”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content” />
</LinearLayout>
package net.learn2develop.WebView;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
<application
android:icon=”@drawable/ic_launcher”
android:label=”@string/app_name” >
<activity
www.it-ebooks.info
Some Additional Views ❘ 245
android:label=”@string/app_name”
android:name=”.WebViewActivity” >
<intent-filter >
<action android:name=”android.intent.action.MAIN” />
</manifest>
How It Works
To use the WebView to load a web page, you use the loadUrl()
method and pass it a URL, like this:
wv.loadUrl(
“http://chart.apis.google.com/chart” +
“?chs=300x225” +
“&cht=v” +
“&chco=FF6342,ADDE63,63C6DE” +
“&chd=t:100,80,60,30,30,30,10” +
“&chdl=A|B|C”);
FIGURE 5-14
To display the built-in zoom controls, you need to first get
the WebSettings property from the WebView and then call its
setBuiltInZoomControls() method:
Figure 5-15 shows the built-in zoom controls that appear when you use the mouse to click and drag the
content of the WebView on the Android emulator.
NOTE While most Android devices support multi-touch screens, the built-in
zoom controls are useful for zooming your web content when testing your
application on the Android emulator.
Sometimes when you load a page that redirects you (for example, loading www.wrox.com redirects
you to www.wrox.com/wileyCDA), WebView will cause your application to launch the device’s Browser
application to load the desired page. In Figure 5-16, note the URL bar at the top of the screen.
www.it-ebooks.info
246 ❘ CHAPTER 5 DISPLAYING PICTURES AND MENUS WITH VIEWS
To prevent this from happening, you need to implement the WebViewClient class and override the
shouldOverrideUrlLoading() method, as shown in the following example:
package net.learn2develop.WebView;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
www.it-ebooks.info
Some Additional Views ❘ 247
Figure 5-17 shows the Wrox.com home page now loading correctly in the WebView.
FIGURE 5-17
You can also dynamically formulate an HTML string and load it into the WebView, using the
loadDataWithBaseURL() method:
www.it-ebooks.info
248 ❘ CHAPTER 5 DISPLAYING PICTURES AND MENUS WITH VIEWS
FIGURE 5-18
Alternatively, if you have an HTML fi le located in the assets folder of the project (see Figure 5-19),
you can load it into the WebView using the loadUrl() method:
FIGURE 5-19
www.it-ebooks.info
Summary ❘ 249
FIGURE 5-20
SUMMARY
In this chapter, you have taken a look at the various views that enable you to display images:
Gallery, ImageView, ImageSwitcher, and GridView. In addition, you learned about the difference
between options menus and context menus, and how to display them in your application. Finally,
you learned about the AnalogClock and DigitalClock views, which display the current time
graphically, as well as the WebView, which displays the content of a web page.
EXERCISES
1. What is the purpose of the ImageSwitcher?
2. Name the two methods you need to override when implementing an options menu in your activity.
3. Name the two methods you need to override when implementing a context menu in your activity.
4. How do you prevent the WebView from invoking the device’s web browser when a redirection
occurs in the WebView?
www.it-ebooks.info
250 ❘ CHAPTER 5 DISPLAYING PICTURES AND MENUS WITH VIEWS
Using the Gallery view Displays a series of images in a horizontal scrolling list
Gallery <Gallery
android:id=”@+id/gallery1”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content” />
ImageView <ImageView
android:id=”@+id/image1”
android:layout_width=”320px”
android:layout_height=”250px”
android:scaleType=”fitXY” />
Using the ImageSwitcher view Performs animation when switching between images
ImageSwitcher <ImageSwitcher
android:id=”@+id/switcher1”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:layout_alignParentLeft=”true”
android:layout_alignParentRight=”true”
android:layout_alignParentBottom=”true” />
GridView <GridView
android:id=”@+id/gridview”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:numColumns=”auto_fit”
android:verticalSpacing=”10dp”
android:horizontalSpacing=”10dp”
android:columnWidth=”90dp”
android:stretchMode=”columnWidth”
android:gravity=”center” />
AnalogClock <AnalogClock
android:layout_width=”wrap_content”
android:layout_height=”wrap_content” />
DigitalClock <DigitalClock
android:layout_width=”wrap_content”
android:layout_height=”wrap_content” />
www.it-ebooks.info