Thứ Ba, 11 tháng 12, 2012
android - cheap 10 -
Expanding the User Experience
WHAT’S IN THIS CHAPTER?
Customizing the Action Bar
Using the Action Bar for application navigation
Using the Android menu system
Choosing Action Bar actions
Creating immersive applications
Creating and displaying Dialogs
Displaying Toasts
Using the Notifi cation Manager to notify users of application events
Creating insistent and ongoing Notifi cations
In Chapter 4, “Building User Interfaces,” you learned how to use Activities, Fragments, lay-
outs, and Views to construct a user interface (UI). To ensure that your UI is stylish, easy to
use, and provides a user experience consistent with the underlying platform and other applica-
tions running in it, this chapter looks at ways to expand the user experience beyond the UI
elements you design.
You’ll start with the Action Bar, introduced in Android 3.0, a system UI component used to
provide a consistent pattern for branding, navigation, and displaying common actions within
your Activities. You’ll learn how to customize the look of the Action Bar, as well as how to use
it to provide navigation with tabs and drop-down lists.
Action Bar actions, application Menus, and Popup Menus use a new approach to menus, opti-
mized for modern touch screen devices. As part of an examination of the Android UI model,
this chapter looks at how to create and use them within your applications. In particular, you’ll learn
how to identify which Menu Items should be displayed as actions on your Action Bar.
Android offers several techniques for applications to communicate with users without an Activity.
You’ll learn how to use Notifi cations and Toasts to alert and update users without interrupting the
active application.
A Toast is a transient, nonmodal dialog-box mechanism used to display information to users with-
out stealing focus from the active application. You’ll learn to display Toasts from any application
component to send unobtrusive on-screen messages to your users.
Whereas a Toast is silent and transient, a Notifi cation represents a more robust mechanism for
alerting users. In many cases, when the user isn’t actively using the mobile phone, it sits silent and
unwatched in a pocket or on a desk until it rings, vibrates, or fl ashes. If a user misses these alerts,
status bar icons are used to indicate that an event has occurred. All these attention-grabbing antics
are available to your Android application through Notifi cations.
You’ll also learn how to customize the appearance and functionality of your Notifi cation when it
appears in the notifi cation tray — providing a mechanism for users to interact with your application
without needing to open it fi rst.
NTRODUCING THE ACTION BAR
The Action Bar component, shown in Figure 10-1, was introduced in Android 3.0 (API level 11). It’s
a navigation panel that replaces the title bar at the top of every Activity and that formalizes a com-
mon Android design pattern.
FIGURE 10-1
It’s possible to hide the Action Bar, but best practice is to keep it and customize it to suit the style
and navigation requirements of your application.
The Action Bar can be added to each Activity within your application and is designed to provide a
consistent UI between applications and within a particular application’s Activities.
The Action Bar provides a consistent framework for providing branding, navigation, and sur-
facing the key actions to be performed within an Activity. Although the Action Bar provides a
framework for presenting this functionality consistently across applications, the following sections
describe how you can select which options are suitable for your application — and how they can be
implemented.
The Action Bar is enabled by default in any Activity that uses the (default) Theme.Holo theme and
whose application has a target (or minimum) SDK version of 11 or higher.
Listing 10-1 shows how to enable the Action Bar by setting the target SDK to Android 4.0.3 (API
level 15) and not modifying the default theme.
<uses-sdk android:targetSdkVersion=”15” />
code snippet PA4AD_Ch10_ ActionBar/AndroidManifest.java
To toggle the visibility of the Action Bar at run time, you can use its show and hide methods:
ActionBar actionBar = getActionBar();
// Hide the Action Bar
actionBar.hide();
// Show the Action Bar
actionBar.show();
Alternatively, you can apply a theme that doesn’t include the Action Bar, such as the Theme.Holo
.NoActionBar theme, as shown in Listing 10-2.
LISTING 10-2: Disabling the Action Bar
<activity
android:name=”.MyNonActionBarActivity”
android:theme=”@android:style/Theme.Holo.NoActionBar”>
code snippet PA4AD_Ch10_ ActionBar/AndroidManifest.java
You can create or customize your own theme that removes the Action Bar by setting the
android:windowActionBar style property to false:
<?xml version=”1.0” encoding=”utf-8”?>
<resources>
<style name=”NoActionBar” parent=”@style/ActivityTheme”>
<item name=”android:windowActionBar”>false</item>
</style>
</resources>
When you apply a theme that excludes the Action Bar from an Activity, you can’t programmatically
display it at run time. A call to getActionBar will return null.
The Action Bar was introduced in Android 3.0 (API level 11) and is not cur-
rently included in the support library. As a result, you can only use the Action
Bar when running on a host platform with at least Android 3.0. One alternative
is to create a different layout for platforms running pre-Android 3.0. The alter-
native layout would need to implement its own custom Action Bar — typically
in the form of a Fragment — to offer similar functionality.
Customizing the Action Bar
In addition to controlling the implementation of this standard functionality, each application can
modify the appearance of the Action Bar while maintaining the same consistent behavior and gen-
eral layout.
One of the primary purposes of the Action Bar is to provide a consistent UI between applications.
As such, the customization options are purposefully limited, though you can customize the Action
Bar to provide your own application branding and identity.
You can control your branding by specifying the image to appear (if any) at the far left, the application
title to display, and the background Drawable to use. Figure 10-2 shows a customized Action Bar that
uses a logo bitmap to identify the application and a Gradient Drawable as a background image.
FIGURE 10-2
Modifying the Icon and Title Text
By default, the Action Bar displays the Drawable you specify using your application or Activity’s
android:icon attribute, alongside the corresponding android:label attribute on a black background.
You can specify an alternative graphic using the android:logo attribute. Unlike the square icon,
there is no limit to the width of the logo graphic — though it’s good practice to limit it to approxi-
mately double the width of the icon image.
The logo image typically is used to provide the top-level branding for your application, so it’s good
practice to hide the title label when using a logo image. You can do this at run time by setting the
Action Bar’s setDisplayShowTitleEnabled method to false:
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(false);
Where both an icon and logo image are supplied, you can switch between them at run time by using
the setDisplayUseLogoEnabled method:
actionBar.setDisplayUseLogoEnabled(displayLogo);
If you choose to hide the icon and logo, you can do so by setting the setDisplayShowHomeEnabled
method to false:
actionBar.setDisplayShowHomeEnabled(false);
The application icon/logo is typically used as a navigation shortcut to the appli-
cation’s main Activity, so it’s good practice to always have it visible.
You also can use the icon and title text to provide navigation and context cues. Use the setTitle
and setSubTitle methods at run time to modify the text displayed alongside the icon, as demon-
strated in Listing 10-3 and shown in Figure 10-3.
actionBar.setSubtitle(“Inbox”);
actionBar.setTitle(“Label:important”);
code snippet PA4AD_Ch10_ActionBar/src/ActionBarActivity.java
FIGURE 10-3
These text strings can be used to describe the users’ location within the application and the context
within which they’re working. This is particularly useful when using Fragments to change context
rather than the traditional Activity stack. The followings sections provide more details regarding
navigation options.
Customizing the Background
The default background color of the Action Bar depends on the underlying theme. The native
Android Action Bar background is transparent, with the Holo theme background set to black.
You can specify any Drawable as the background image for your Action Bar by using the
setBackgroundDrawable method, as shown in Listing 10-4.
LISTING 10-4: Customizing the Action Bar background
ActionBar actionBar = getActionBar();
Resources r = getResources();
Drawable myDrawable = r.getDrawable(R.drawable.gradient_header);
actionBar.setBackgroundDrawable(myDrawable);
code snippet PA4AD_Ch10_ActionBar/src/ActionBarActivity.java
The Action Bar will scale your image, so it’s best practice to create a scalable Drawable, typically
using either a 9-patch or XML defi ned Drawable. Both alternatives are explored in more detail in
Chapter 11, “Advanced User Experience.”
Under normal circumstances the Action Bar will reserve space at the top of your Activity, with your
layout being infl ated into the remaining space. Alternatively, you can choose to overlay the Action
Bar above your Activity layout by requesting the FEATURE_ACTION_BAR_OVERLAY window feature.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
setContentView(R.layout.main);
}
When the overlay mode is enabled, the Action Bar will fl oat above your Activity, potentially obscur-
ing content at the top of your layout.
Enabling the Split Action Bar Mode
The Action Bar was initially introduced in Android 3.0 — a platform release that was focused on
providing the best user experience possible for tablet devices. Android 4.0 (API level 14) sought to
optimize many of the features initially designed for tablets for use on smaller, smartphone devices.
For the Action Bar, this meant the introduction of the split Action Bar. You can enable the split
Action Bar by setting the android:uiOptions attribute within your application or Activity manifest
nodes to splitActionBarWhenNarrow, as shown in Listing 10-5.
LISTING 10-5: Enabling the split Action Bar
<activity
android:label=”My Activity”
android:name=”.ActionBarActivity”
android:logo=”@drawable/ic_launcher”
android:uiOptions=”splitActionBarWhenNarrow”>
code snippet PA4AD_Ch10_ ActionBar/AndroidManifest.xml
On supported devices with narrow screens (such as a smart-
phone in portrait mode), enabling the split Action Bar mode
will allow the system to split the Action Bar into separate sec-
tions. Figure 10-4 shows an example of an Action Bar that has
been laid out with the branding and navigation sections layered
at the top of the screen, with the action sections aligned to the
bottom of the screen.
The layout is calculated and performed by the run time and
may change depending on the orientation of the host device
and any Action Bar confi guration changes you make at run
time.
Customizing the Action Bar to Control
Application Navigation Behavior
The Action Bar introduces a several options for providing
consistent and predictable navigation within your applica-
tion. Broadly speaking, those options can be divided into two
categories:
Application icons — The application icon or logo is used to provide a consistent navigation
path, typically by resetting the application to its home Activity. You can also confi gure the
icon to represent moving “up” one level of context.
FIGURE 10-4
Tabs and drop-downs — The Action Bar supports built-in tabs or drop-down lists that can
be used to replace the visible Fragments within an Activity.
Icon navigation can be considered a way to navigate the Activity stack, whereas tabs and drop-
downs are used for Fragment transitions within an Activity. In practice, the actions you perform
when the application icon is clicked or a tab is changed will depend on the way you’ve implemented
your UI.
Selecting the application icon should change the overall context of your UI in the same way that an
Activity switch might do, whereas changing a tab or selecting a drop-down should change the data
being displayed.
Confi guring Action Bar Icon Navigation Behavior
In most cases, the application icon should act as a shortcut to return to the “home” Activity, typi-
cally the root of your Activity stack. To make the application icon clickable, you must call the
Action Bar’s setHomeButtonEnabled method:
actionBar.setHomeButtonEnabled(true);
Clicking the application icon/logo is broadcast by the system as a special Menu Item click. Menu
Item selections are handled within the onOptionsItemSelected handler of your Activity, with the
ID of the Menu Item parameter set to android.R.id.home, as shown in Listing 10-6.
The process of creating and handling Menu Item selections is described in more detail later in this
chapter.
LISTING 10-6: Handling application icon clicks
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case (android.R.id.home) :
Intent intent = new Intent(this, ActionBarActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
code snippet PA4AD_Ch10_ActionBar/src/ActionBarActivity.java
Traditionally, Android applications have started a new Activity to transition between different
contexts. In turn, pressing the back button closes the active Activity and returns to the
previous one.
To supplement this behavior, you can confi gure the application icon to offer “up” navigation.
The back button should always move the user back through contexts (typically in the form of
Activities) that they have already seen, effectively reversing the navigation path they followed to
arrive at the current Activity or screen. This might result in navigation between “siblings” in your
application structure.
In contrast, “up” navigation should always move users to the parent of the current Activity. As a
result, it can move users to a screen they have not previously visited. This is particularly useful for
applications with multiple entry points, allowing users to navigate within an application without
having to return to the application that spawned it.
To enable up navigation for your application icon, call the Action Bar’s setDisplayHomeAsUp-
Enabled method:
actionBar.setDisplayUseLogoEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(true);
This has the effect of overlaying an “up” graphic over your application icon, as shown in
Figure 10-5. Note that it’s good practice to use the icon rather than the logo when enabling up
navigation.
FIGURE 10-5
Handling the navigation is left to you to implement. The Action Bar will still trigger the onOptions-
ItemSelected handler with a Menu Item that uses android.R.id.home as its identifi er, as shown
in Listing 10-6.
Such behavior introduces certain risks, particularly if there are multiple ways a user may have navi-
gated to a particular Activity. If in doubt, the up behavior should mirror the back button. In all
cases, the navigation behavior should be predictable.
Using Navigation Tabs
In addition to the application icon navigation, the Action Bar also offers navigation tabs and drop-
down lists. Note that only one of these forms of navigation can be enabled at once. These navigation
options are designed to work closely with Fragments, providing a mechanism for altering the con-
text of the current Activity by replacing the visible Fragments.
Navigation tabs (shown in Figure 10-6) can be considered a replacement for the TabWidget
control.
FIGURE 10-6
To con fi gure your Action Bar to display tabs, call its setNavigationMode method, specifying
ActionBar.NAVIGATION_MODE_TABS. The tabs should provide the application context, so it’s good
practice to disable the title text as well, as shown in Listing 10-7.
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowTitleEnabled(false);
code snippet PA4AD_Ch10_ActionBar/src/ActionBarTabActivity.java
Tabs are added to the Action Bar using its addTab method, as shown in Listing 10-8. Start by creat-
ing a new Tab and using its setText and setIcon methods to determine the title and image to be
displayed, respectively. Alternatively, you can use the setCustomView method to replace the stan-
dard text and image layout with your own custom View.
LISTING 10-8: Adding Action Bar navigation tabs
Tab tabOne = actionBar.newTab();
tabOne.setText(“First Tab”)
.setIcon(R.drawable.ic_launcher)
.setContentDescription(“Tab the First”)
.setTabListener(
new TabListener<MyFragment>
(this, R.id.fragmentContainer, MyFragment.class));
actionBar.addTab(tabOne);
code snippet PA4AD_Ch10_ActionBar/src/ActionBarTabActivity.java
Android 4.0 (API level 14) introduced the setContentDescription method,
which allows you include a more detailed content description to better support
accessibility.
The tab switching is handled using a TabListener, allowing you to create Fragment Transactions in
response to tabs being selected, unselected, and reselected, as shown in Listing 10-9. Note that you
are not required to execute the Fragment Transaction created in each handler — the Action Bar will
execute it for you when necessary.
LISTING 10-9: Handling Action Bar tab switching
public static class TabListener<T extends Fragment>
implements ActionBar.TabListener {
private MyFragment fragment;
private Activity activity;
private Class<T> fragmentClass;
continues
private int fragmentContainer;
public TabListener(Activity activity, int fragmentContainer,
Class<T> fragmentClass) {
this.activity = activity;
this.fragmentContainer = fragmentContainer;
this.fragmentClass = fragmentClass;
}
// Called when a new tab has been selected
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if (fragment == null) {
String fragmentName = fragmentClass.getName();
fragment =
(MyFragment)Fragment.instantiate(activity, fragmentName);
ft.add(fragmentContainer, fragment, null);
fragment.setFragmentText(tab.getText());
} else {
ft.attach(fragment);
}
}
// Called on the currently selected tab when a different tag is
// selected.
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (fragment != null) {
ft.detach(fragment);
}
}
// Called when the selected tab is selected.
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO React to a selected tab being selected again.
}
}
code snippet PA4AD_Ch10_ActionBar/src/ActionBarTabActivity.java
The basic workfl ow used within this Tab Listener is to instantiate, confi gure, and then add a new
Fragment to your layout within the onTab-
Selected handler. The Fragment associated with
the unselected tab should be detached from your
layout and recycled if its tab is reselected.
Using Drop-Down Lists for Navigation
You can use an Action Bar drop-down list, as shown
in Figure 10-7, as an alternative to the navigation
tabs or as ideal solutions for applying in-place fi lters
to content being displayed within your Activity.
FIGURE 10-7
LISTING 10-9 (continued)
To con fi gure your Action Bar to display a drop-down list, call its setNavigationMode method,
specifying ActionBar.NAVIGATION_MODE_LIST:
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
The drop-down list is implemented much like a Spinner — a view that displays one child at a
time and lets the user pick from among them. Populate the drop-down list by creating a new
Adapter that implements the SpinnerAdapter interface, such as an Array Adapter or Simple
Cursor Adapter:
ArrayList<CharSequence> al = new ArrayList<CharSequence>();
al.add(“Item 1”);
al.add(“Item 2”);
ArrayAdapter<CharSequence> dropDownAdapter =
new ArrayAdapter<CharSequence>(this,
android.R.layout.simple_list_item_1,
al);
To assign the Adapter to your Action Bar, and handle selections, call the Action Bar’s setList-
NavigationCallbacks, passing in your adapter and an OnNavigationListener, as shown in
Listing 10-10.
LISTING 10-10: Creating an Action Bar drop-down list
// Select the drop-down navigation mode.
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
// Create a new Spinner Adapter that contains the values to
// be displayed in the drop down.
ArrayAdapter dropDownAdapter =
ArrayAdapter.createFromResource(this,
R.array.my_dropdown_values,
android.R.layout.simple_list_item_1);
// Assign the callbacks to handle drop-down selections.
actionBar.setListNavigationCallbacks(dropDownAdapter,
new OnNavigationListener() {
public boolean onNavigationItemSelected(int itemPosition,
long itemId) {
// TODO Modify your UI based on the position
// of the drop down item selected.
return true;
}
});
code snippet PA4AD_Ch10_ActionBar/src/ActionBarDropDownActivity.java
When a user selects an item from the drop-down list, the onNavigationItemSelected handler will
be triggered. Use the itemPosition and itemId parameters to determine how your UI should be
adapted based on the new selection.
Drop-down list selections typically are used to refi ne existing content, such as to select a particular
account or label within an email client.
Using Custom Navigation Views
For situations where neither tabs nor drop-down lists are appropriate, the Action Bar allows you to
add your own custom View (including layouts) using the setCustomView method:
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setCustomView(R.layout.my_custom_navigation);
Custom Views will appear in the same place as the tabs or drop-down lists — to the right of the
application icon but to the left of any actions. To ensure consistency between applications, it’s gener-
ally good form to use the standard navigation modes.
Introducing Action Bar Actions
The right side of the Action Bar is used to display “actions” and the associated overfl ow menu, as
shown in Figure 10-8.
Action Menu
Items
Overflow
Menu
FIGURE 10-8
Action Bar actions and the overfl ow menu were introduced, along with the Action Bar itself, in
Android 3.0 (API level 11) as an alternative to the hardware menu button and its associated options
menu. As such, they are populated using the same APIs that were previously used to create and man-
age the options menu. This process is described in detail later in this chapter.
Actions, then, are Menu Items that are important enough to make them visible and easily available
to users at all times. Action items should be menu options that are either most frequently used, most
important for users to discover, or most expected based on the actions available in similar applica-
tions. Generic and seldom used options, such as settings, help, or “about this app” options, should
never be presented as action items.
Generally speaking, action items should be global actions that don’t depend on the current context.
Navigating within an Activity — for example, changing tabs or selecting an item from a navigation
drop-down — should not alter the available action items.
ADDING AN ACTION BAR TO THE EARTHQUAKE MONITOR
In the following example, the earthquake-monitoring application, whose processing you moved to the
background in Chapter 9, “Working in the Background,” will be enhanced to include an Action Bar.
Đăng ký:
Đăng Nhận xét (Atom)
Không có nhận xét nào:
Đăng nhận xét