SlideShare a Scribd company logo
Mobile Application Development
Chapter 4: App User Interface
LEARNING OBJECTIVES
After completing this chapter, you will be able to:
• Create basic user interface of Android app.
• Illustrate Activity life cycle.
• Devise interaction among Activities using Intents.
• Compose tablet UI using Fragments and action bar.
This chapter primarily focuses on user interface aspects of an app
that contribute to a rich user experience.
• It starts with the core building block of Android UI – Activity –
and further delves into layouts and other UI elements that are
required for designing the screen makeup.
Activity
• An activity represents a single screen with a user interface just like window
or frame of java. Android activity is the subclass of ContextThemeWrapper
class.
• An activity is a window that contains the user interface of your
applications.
• An application can have zero or more activities. Typically, applications
have one or more activities, and the main aim of an activity is to interact
with the user. From the moment
• When the user taps on an app icon, the designated Activity gets launched
into the foreground where it has the user focus. Pressing the Back key
destroys the Activity in focus (current Activity) and displays the previous
Activity to the user. Pressing the Home key moves the Activity in focus to
the background, navigating to the Home screen.
[[References]
• package android.view;
• import android.content.Context;
• import android.content.ContextWrapper;
• import android.content.res.Resources;
• /**
• * A ContextWrapper that allows you to modify the theme from what is in the
wrapped context.
• */
• public class ContextThemeWrapper extends ContextWrapper {
• private Context mBase;
• private int mThemeResource;
• private Resources.Theme mTheme;
• private LayoutInflater mInflater;
• public ContextThemeWrapper() {
• super(null);
• }
•
• public ContextThemeWrapper(Context base, int themeres) {
• super(base);
• mBase = base;
• mThemeResource = themeres;
• From the moment an activity appears on the screen to the moment it is
hidden, it goes through a number of stages.
• These stages are known as an activity’s life cycle.
One has to understanding the life cycle of an activity is vital to
ensuring that your application works correctly.
To create an activity, you create a Java class that extends the
Activity base class:
1 package com.mad.firstapp;
2 import android.os.Bundle;
3 import android.app.Activity;
4 import android.view.Menu;
5 public class MainActivity extends Activity {
6 @Override
7 protected void onCreate(Bundle savedInstanceState) {
8 super.onCreate(savedInstanceState);
9 setContentView(R.layout.activity_main);
10 }
11 ...
12 }
[[References]
• The savedInstanceState is a reference to a Bundle object that is
passed into the onCreate method of every Android Activity.
Activities have the ability, under special circumstances, to
restore themselves to a previous state using the data stored in
this bundle.
• onCreate is used to start an activity. super is used to call the
parent class constructor. setContentView is used to set the xml.
• protected because logically it should not be accessed by other
class different from Activities. ... The onClick is public because it
could be set or handled by external classes that not necessary are
your Activity.
]
[[References]
onCreate(Bundle savedInstanceState) Function in Android:
• When an Activity first call or launched then onCreate(Bundle
savedInstanceState) method is responsible to create the activity.
• When ever orientation(i.e. from horizontal to vertical or vertical
to horizontal) of activity gets changed or when an Activity gets
forcefully terminated by any Operating System then
savedInstanceState i.e. object of Bundle Class will save the state
of an Activity.
• After Orientation changed then onCreate(Bundle
savedInstanceState) will call and recreate the activity and load
all data from savedInstanceState.]
• [[References]
• Basically Bundle class is used to stored the data of activity whenever above
condition occur in app.
• onCreate() is not required for apps. But the reason it is used in app is
because that method is the best place to put initialization code.
• You could also put your initialization code in onStart() or onResume() and
when you app will load first, it will work same as in onCreate().]
• Your activity class loads its user interface (UI) component using the XML
file defined in your res/layout folder.
• In this example, you would load the UI from the main.xml file:
• setContentView(R.layout.activity_main);
MD-IV-CH-ppt.ppt
• [[References]
• This is the XML optional preamble. version="1.0" means that this is the XML
standard. This file conforms to. encoding="utf-8" means that the file is
encoded using the UTF-8 Unicode encoding.
• The encoding declaration
If no encoding declaration exists in a document's XML declaration,
that XML document is required to use either UTF-8 or UTF-16 encoding.
• UTF stands for UCS Transformation Format, and UCS itself means Universal
Character Set. The number 8 or 16 refers to the number of bits used to
represent a character. They are either 8(1 to 4 bytes) or 16(2 or 4 bytes).
• For the documents without encoding information, UTF-8 is set by default.]
• 1 <?xml version=“1.0” encoding=”utf-8”?>
• 2 <manifest
• xmlns:android=“http://schemas.android.com/apk/res/android”
• 3 package=“com.mad.firstapp”
• 4 android:versionCode=“1”
• 5 android:versionName=“1.0”>
• 6
• 7 <uses-sdk
• 8 android:minSdkVersion=“8”
• 9 android:targetSdkVersion=“18”/>
• 10
• 11 <application
• 12 android:allowBackup=“true”
• 13 android:icon=“@drawable/ic_launcher”
• 14 android:label=“@string/app_name”
• 15 android:theme=“@style/AppTheme” >
16 <activity
17 android:name=“com.mad.firstapp.MainActivity”
18 android:label=“@string/app_name”>
19 <intent-filter>
20 <action
android:name=“android.intent.action.MAIN”/>
21
22 <category
android:name=“android.intent.category.LAUNCHER”/>
23 </intent-filter>
24 </activity>
25 </application>
26
27 </manifest>
Snippet 2.5 AndroidManifest.xml.
[[References]
xmlns:android=“http://schemas.android.com/apk/res/android”
In XML, xmlns declares a Namespace. In fact, when you do:
• <LinearLayout android:id>
• </LinearLayout>
• Instead of calling android:id, the xml will
use http://schemas.android.com/apk/res/android:id to be unique. Generally this page doesn't
exist (it's a URI, not a URL), but sometimes it is a URL that explains the used namespace.
• The namespace has pretty much the same uses as the package name in a Java application.
• Here is an explanation.
• Uniform Resource Identifier (URI)
• A Uniform Resource Identifier (URI) is a string of characters which identifies an Internet
Resource.
• The most common URI is the Uniform Resource Locator (URL) which identifies an Internet
domain address.
• Another, not so common type of URI is the Universal Resource Name (URN).
• ]
[[References]
12 android:allowBackup=“true”
The allowBackup attribute determines if an application's data
can be backed up and restored,
By default, this flag is set to true. When this flag is set to true,
application data can be backed up and restored by the user
using adb backup and adb restore.
• This may have security consequences for an application.
• adb backup allows users who have enabled USB debugging to
copy application data off of the device.
• Once backed up, all application data can be read by the user.
• adb restore allows creation of application data from a source
specified by the user.
• Cont…..
Following a restore, applications should not assume that the data, file
permissions, and directory permissions were created by the application itself.
Setting allowBackup="false" opts an application out of both backup and
restore.
To fix this warning, decide whether your application should support backup
and explicitly set android:allowBackup=(true|false)
]]
[[References]
Android Intent
android:name=“android.intent.action.MAIN”/>
• Android Intent is the message that is passed between
components such as activities, content providers, broadcast
receivers, services etc. It .
• android. intent. action. MAIN means that this activity is the
entry point of the application, i.e. when you launch the
application, this activity is created
• Main is action intent and Launcher is category of the intent.
Main tells operating system that the activity is main activity of
the application, Launcher tells the operating system that the
activity should be visible in the launcher of the phone.
• android:name=“android.intent.category.LAUNCHER”/> ]
Summary:
Key points about this file are as below:
• It defines the package name of the
application as “com.mad.firstapp”
• The version code of the application is 1. This value is used to
identify the version number of your application. It can be used to
programmatically determine whether an application needs to be
upgraded.
• The version name of the application is 1.0. This string value is
mainly used for display to the user.
• The application uses the image named ic_launcher.png located in
the drawable folder.
• The name of this application is the string named app_name
defined in the strings.xml file.
• There is one activity in the application represented by the
MainActivity.java file. The label displayed for this activity is the same as
the application name.
• Within the definition for this activity, there is an element named <intent-
filter>:
• The action for the intent filter is named android.intent.action.MAIN to
indicate that this activity serves as the entry point for the application.
• The category for the intent-filter is named
android.intent.category.LAUNCHER to indicate that the application
can be launched from the device’s Launcher icon.
• Finally, the android:minSdkVersion attribute of the <uses-sdk> element
specifies the minimum version of the OS on which the application will run.
The Activity base class defines a series of events that govern the life cycle of
an activity. Figure 3-1 shows the lifecycle of an Activity.
The Activity class defines the following events:
• onCreate()—Called when the activity is first created
• onStart()—Called when the activity becomes visible to the user
• onResume()—Called when the activity starts interacting with the
user
• onPause()—Called when the current activity is being paused and
the previous activity is being resumed
• onStop()—Called when the activity is no longer visible to the user
• onDestroy()—Called before the activity is destroyed by the
system (either manually or by the system to conserve memory)
• onRestart()—Called when the activity has been stopped and is
restarting again
• By default, the activity created for you contains the onCreate() event.
Within this event handler is the code that helps to display the UI elements
of your screen.
Understanding Life Cycle of an Activity using an Example
Let us now explore these life-cycle methods using Snippet 4.1. All six life-
cycle methods are overridden, and
• In each method a log statement –
Log.i (String tagname, String message)
– has been placed to reflect the life-cycle method and state, as transition
happens.
• The log messages are displayed in the LogCat utility in Dalvik Debug
Monitor Server (DDMS).
MD-IV-CH-ppt.ppt
MD-IV-CH-ppt.ppt
MD-IV-CH-ppt.ppt
MD-IV-CH-ppt.ppt
MD-IV-CH-ppt.ppt
When we run Snippet 4.1 and observe the LogCat,
• we see that three life-cycle methods (onCreate, onStart, and
onResume)
• Get executed as soon as the app is launched, as shown in Fig. 4.2.
Figure 4.2 LogCat view depicting methods execution on app launch.
The first method to get executed is onCreate().
• This is executed only once during the lifetime of an Activity, that
is, at the beginning, when the Activity is launched.
• If we have any instance variables in the Activity, the
initialization of those variables can be done in this method.
After onCreate(), the onStart() method is executed.
• During the execution of onStart(), the Activity is not yet rendered
on screen but is about to become visible to the user.
• In this method, we can perform any operation related to UI
components.
• When the Activity finally gets rendered on the screen,
onResume() is invoked.
• At this point, the Activity is in the active state and is interacting
with the user.
• If the Activity loses its focus and is only partially visible to the user, it
enters the paused state. During
• this transition, the onPause() method is invoked. In the onPause() method,
we may commit database
• transactions or perform light-weight processing before the Activity goes to
the background.
• When the Activity comes back to focus from the paused state, onResume()
is invoked. This transition
• between paused and active states is a frequent phenomenon, thus
onResume() is called more often than
• any other life-cycle method of an Activity. Because of this reason, it is
advisable to keep the implementation
• of onResume() as light as possible.
• From the active state, if we hit the Home key, the Activity goes to the
background and the Home screen
• of the device is made visible. During this event, the Activity enters the
stopped state. Both onPause() and
• onStop() methods are executed, as shown in Fig. 4.3.
• When we reopen the app,[1] we observe that the Activity is now
transitioning from the stopped state to the active state.
• This is characterized by invocation of only onStart() and onResume()
methods (see Fig. 4.4),
• Validating that onCreate() gets invoked only once in a lifetime of the
Activity.
Note: Either by tapping the app icon or by long pressing of Home key and
selecting the running app
• To destroy the Activity on the screen, we can hit the Back key. This
moves the Activity into the destroyed state.
• During this event, onPause(), onStop(), and onDestroy() methods are
invoked, as shown in Fig. 4.5.
• You may recall that, in the destroyed state, the Android runtime marks
the Activity to become eligible to go out of memory.
To summarize, the Activity is alive from onCreate() to onStop() methods and
depending upon how many times the Activity goes to the background or loses
focus and comes back to the foreground, onStart(),
onResume(), onPause(), and onStop() methods get executed. When an Activity is
destroyed, the onDestroy() method is called. Once an Activity is destroyed, it has
to be recreated to return to the active state.
• As there may be a flurry of messages that may get generated in LogCat, it
would be convenient to filter the app-specific log messages.
• To add a new filter, click on + sign of the Saved Filters view, as depicted in
Fig. 4.6. This will open the Logcat Message Filter Settings dialog box, as
depicted in Fig. 4.7.
• Enter a relevant name in the Filter Name field (Fig. 4.7). This
name will appear in the Saved Filters view,as depicted in Fig.
4.8.
• The LogCat message can be filtered in various ways, but we are
using filter by LogTag.
• Enter the tagname parameter (refer to Snippet 4.1) of Log.i()[2]
in the by Log Tag field, as depicted in Fig. 4.7.
• Select info in by Log Level drop-down; this corresponds to the log
level selected in Snippet 4.1.
• Click OK in the Logcat Message Filter Settings dialog box to save
the filter, as depicted in Fig. 4.8.
Note: [2] i in Log.i stands for info.
The LogCat outputs shown in Figs. 4.2–4.5 were captured after applying the
filter. Having understood the core programming component of UI (Activity),
its states and life-cycle methods
UI RESOURCES
• User interface resources are typically the nonprogramming
components of UI that help a developer in laying out the visual
structure of screens, along with string constants and images that
populate these screens.
• There are other UI resources such as menu that provide different
ways of user interaction and navigation in apps.
UI Resources are
• Layout Resources
• String Resources
• Image Resources
Layout Resources
• Layout resource provides a visual blueprint for an Activity and
defines how the UI elements in a screen is arranged.
• Layout resources are XML files located in the reslayout folder.
• A layout file may be associated with one or more Activities.
• You may recall the
setContentView(R.layout.activity_main)
Method that associates an Activity with a layout file (activity_main.xml).
• Upon creating a layout resource, Android framework generates a
unique id for it in the R.java file present in the gen folder.
• The R.java file contains information about all nonprogramming
components, using which a developer can resolve these resources
inside programming components.
For example, if a layout file is named activity_main.xml, it is
represented as an integer constant – public static final int
activity_main – in the R.java file under a static class – layout. This
is applicable to all nonprogramming components.
[[References-two slides about R.java file]
• gen — Contains the R.java file, a compiler-generated file that
references all the resources found in your project. You should not
modify this file.
• R.java File: As you add more files and folders to your project,
Eclipse will automatically generate the content of R.java, which
at the moment contains the following:
• You are not supposed to modify the content of the R.java file;
Eclipse automatically generates the content for you when you
modify your project.
• package net.learn2develop.HelloWorld;
• public final class R {
• public static final class attr {
• }
• public static final class drawable {
• public static final int icon=0x7f020000;
• }
• public static final class layout {
• public static final int main=0x7f030000;
• }
• public static final class string {
• public static final int app_name=0x7f040001; public static final int
hello=0x7f040000;
• } }
• Snippet 4.2 depicts a sample layout file – activity_main.xml – and the
resultant integer constant in the R.java file is listed in Snippet 4.3.
Android provides the Layout editor[3] to create the layouts.
To create a new layout file, right click on the layout folder of Android app
project structure, and then select New → Android XML File, which will pop
up the New Android XML File wizard, as depicted in Fig. 4.9.
Note: DroidDraw is another popular open source to create layouts.
MD-IV-CH-ppt.ppt
• The Layout editor also provides a mechanism to drag and drop the UI
components in the layout file to create the required UI. The equivalent
XML layout file gets generated automatically behind the scenes.
• Because apps have different requirements for arranging the UI elements
(referred to as views in Android context), the Layout editor provides
various ready-to-use layouts such as relative, linear, grid, and table.
• Relative layout is the default layout of an Activity wherein views (UI
elements) are arranged relative to other views in that layout and/or the
layout itself. Because views are always placed relative to one another,
rendering views happens automatically without any hassles on devices of
diverse screen resolutions, sizes, or orientations.
• LinearLayout : Arranges views in a single column or single row.
• AbsoluteLayout : Enables you to specify the exact location of its children.
• TableLayout: Groups views into rows and columns.
• RelativeLayout : Enables you to specify how child views are positioned
relative to each other. Or RelativeLayout is a view group that displays child
views in relative positions.
• FrameLayout: A placeholder on screen that you can use to display a single
view.
• ScrollView: A special type of FrameLayout in that it enables users to scroll
through a list of views that occupy more space than the physical display
allows.
• Unit of Measure : Use dp for specifying the dimension of views and sp for
font size.
RelativeLayout
• To create a relative layout, select RelativeLayout as the root
element from New Android XML File wizard, as already explored
in Fig. 4.9. This will yield an XML file with RelativeLayout as
the root element.
• When we use relative layout, there are two types of attributes
that can be assigned to views –
• To align views relative to one another in the layout or
• To align views relative to the layout itself.
• For example, as depicted in Fig. 4.10 and Snippet 4.4,
• EditText1 is placed relative to its container (RelativeLayout),
whereas Button1 and Button2 are placed relative to other views
(EditText1 and Button1, respectively).
Figure 4.10 LayoutDemo app.
MD-IV-CH-ppt.ppt
MD-IV-CH-ppt.ppt
• In Snippet 4.4, EditText1 contains properties such as
• layout_alignParentLeft,
• layout_alignParentRight, and
• layout_alignParentTop
• set to true
• (Lines 11–13),This ensures that the EditText1 is aligned to the left, right, and
top of the parent (RelativeLayout).
• Button1 is aligned to the right of its parent (RelativeLayout) using the
layout_alignParentRight (Line 21) attribute and
• below EditText1 using the layout_below attribute (Line 22).
• Button2 is placed to the left of Button1 using the layout_toLeftOf attribute (Line
30).
• The layout_alignBaseline and layout_alignBottom attributes (Lines 28 and
29) ensure that the baseline and bottom edge of Button2 are matched with
those of Button1 so that both views are in the same line.
Linear layout
On the other hand, linear layout ensures that UI elements are
placed either horizontally or vertically.
• It is defined by using the LinearLayout tag in the layout file.
• Snippet 4.5 shows how the linear layout canbe used to recreate
the screen of LayoutDemo app (shown in Fig. 4.10).
MD-IV-CH-ppt.ppt
MD-IV-CH-ppt.ppt
• The most important attribute of the linear layout is android:orientation
(Line 4).
• Using this attribute, we can place the elements horizontally or vertically in
the layout. Here, we have set it to vertical.
• We can also see that layouts can be nested (see Line 13). The parent
LinearLayout now hosts a child
• LinearLayout, which in turn contains the two buttons: Button1 and
Button2.
• Another important attribute of the LinearLayout is android:gravity.
• Gravity refers to the alignment of child elements in a container.
• In Line 16, the child LinearLayout’s gravity is set as right so that all child
elements of this layout would be aligned to the right.
String Resources
•String resource XML files are kept in resvalues folder.
To create a string resource XML file,
•Right click on values folder,
•Select New → Android XML File, and
•Provide the appropriate values in New Android XML File wizard (shown
earlier in Fig. 4.9). Editing of this XML file can be done either in a visual
XML file editor or a simple text-based editor.
• Two most commonly used string resources are string constants
and string arrays.
• String constant is a simple key–value pair.
• You may recall from Snippet 2.4 of Chapter 2 that in the
HelloWorld app, string “Helloworld!” is being assigned to the
hello_world key in strings.xml resource file, under the
<resources> tag.
• Similar to a layout resource, a unique id is generated for string
constants in the R.java file that may be further used to
programmatically access it, as depicted in Snippet 4.6.
.
1 Resources resources=getResources();
2 String message1=resources.getString(R.string.hello);
Snippet 4.6 Accessing string constant programmatically
• The method getResources() of Resources class is used to access all
app resources that are present in the app project structure.
• The string resource is further extracted using the getString()
method by passing the unique id of string constant (R.string.hello)
generated in the R.java file (see Line 2 of Snippet 4.6).
• String array is an array of strings assigned to a key.
• It is declared in the string resource file using the <string-array> tag, as depicted
in Snippet 4.7.
• The individual strings in the array are declared using the <item> tag.
• The key is declared as name attribute of the <string-array> tag.
• The string array resource is extracted from the Resources object using the
getStringArray() method by passing the unique id of string array constant
(R.array.nations) generated in the R.javafile, as depicted in Line 2 of Snippet 4.8.
• String resources are also useful in localizing an app in the case of
multilingual rollout.
• This is done by placing string resources in locale-specific resource folders
such as resvalues-fr and resvalues-hi for French and Hindi, respectively.
• All locale equivalents of a specific string resource will use the same key so
that Android runtime automatically picks up the appropriate value based on
the locale.
• Image Resources
• The very first place where a user interacts with an image resource is the app
icon itself.
• There are several other places where images can be incorporated such as in
• Image view,
• Layout background,
• Button,
• And some other UI elements to enhance the visual appeal of an app.
• Image files are placed in resdrawable folders.
• Android provides a mechanism to access these images in app
components programmatically or nonprogrammatically.
• Programmatically, Resources class is used to access an image
resource using the getDrawable() method (see Snippet 4.9).
• The return type of this method is Drawable.
• The unique id of image resource (R.drawable.filename) has to be
passed as parameter to this method.
• In this example, ic_launcher is the filename that represents the
app icon.
1 Drawable drawable=resources.getDrawable(R.drawable.ic_launcher);
Snippet 4.9 Accessing image resource programmatically.
• Nonprogrammatically, an image resource is associated with other UI resources
or elements in the layout file to set the background of layout or other UI
elements, or to display the image itself.
• Using @drawable/ filename as the value to the properties that set the
background (android:background) of a view, an image resource can be set as
the background.
• An example of this is shown in Snippet 4.10.
• We will take a further deep dive into image resources along with other
nitty-gritties of graphics and animations in Chapter 7.
• After having an understanding of Activity and UI resources, let us now
explore UI elements and associated events to create a functional UI.
UI ELEMENTS AND EVENTS
• Android provides views to handle data and user interaction for a
functional UI.
• The user interaction may happen in multiple forms –
• Data entry in an editable view,
• Display of textual/visual data, or
• Triggering of an event based on user actions such as
• click of a button,
• drag of a list, or
• multitouch gestures.
• Any user interaction with a view triggers an event associated with it.
• Such events need to be handled by a developer to provide required
functionalities in views.
Event-Handling Paradigm
• Each view in Android is an event source.
• The event source (view) generates an event object in response to
a user action.
• This event object is passed on to an event listener, provided this
view has registered for that event listener.
• Event listener is a specialized interface designed to listen to the
generated event, and respond to it through callback methods,
also referred to as event handlers.
The event-handling paradigm and its related vocabulary are
summarized in below Table.
UI Elements
• UI elements are declared in layout files.
• The Layout editor provides a mechanism to drag and drop the
required UI components into the layout.
• The equivalent XML representing the UI element gets generated
automatically in the associated layout file.
• Commonly used attributes of a view
• layout_width attribute is set to fill_parent, which makes its width occupy
the entire width of the screen.
• The layout_width attribute is set to wrap_content so that its width will be
the width of its content—specifically, the text that is displayed. (for
example, Open):
• match_parent takes entire screen
Button
Button, as we have seen earlier, is created using the <Button> tag in a
layout file, as also depicted in Snippet
• We can access the Button created in a layout resource using the
findViewById(int) method.
• This method takes the unique id of the Button (Line 2 of Snippet
4.11) as parameter.
• The return type of this method is View, and to assign it to a Button
reference variable, we have to typecast it to a Button, as
• A user can perform various actions on the Button.
• One of the most common actions is to click it.
• To make a Button respond to the click event, we need to set a listener on it.
• The listener associated with handling click events is the OnClickListener.
• To set the listener on a Button, we can either let the Activity hosting it
implement the OnClickListener interface or pass an anonymous inner class
as parameter to the setOnClickListener() method of the Button as shown in
Snippet 4.13.
The onClick() method is the event handler that is automatically executed
when a user clicks the Button.
EditText is an Android component used to accept user input. It is created using
the <EditText> tag in the layout file as depicted in Snippet 4.14.
The findViewById(int) method is used to access the EditText, as
shown in Snippet 4.15.
As we have seen earlier that the findViewById(int) method returns
a View object, therefore we need to typecast this returned object to
EditText.
1 EditText editText1=(EditText) findViewById(R.id.editText1);
Snippet 4.15 Accessing an EditText.
• We use the getText() method to get the text entered by the user, as
shown in Snippet 4.16.
1 String enteredText=editText1.getText().toString();
Snippet 4.16 Getting the text entered in EditText.
• We may also want to set listeners for various actions on EditText.
• One of the common actions is when the user changes the focus
away from the view.
• The event, listener, and handler associated with this event are
specified in Table 4.3, and the respective implementation is shown
in Snippet 4.17.
MD-IV-CH-ppt.ppt
Checkbox is an Android component that accepts user input choices.
It is created using the <CheckBox> tag in the layout file as depicted
in Snippet 4.18.
• We can access a CheckBox by using the findViewById(int)
method and typecasting the resulting View, as shown in Snippet
4.19.
• The most common event on a CheckBox is the CheckedChange event, that
is, switching of its state from checked to unchecked or vice versa.
• The event, listener, and handler are described in Table 4.4.
MD-IV-CH-ppt.ppt
RadioGroup : is used to define a set of options among which only one
can be chosen by the user.
• A RadioGroup in turn contains many RadioButtons, which are
defined in the layout using the <RadioGroup> and
<RadioButton> tags, respectively, as shown in Snippet 4.21.
• A RadioGroup defined in the layout file is accessed using the
findViewById(int) method.
• The View returned from this method is typecasted into
RadioGroup so that desired operations can be performed on the
obtained view. Snippet 4.22 depicts how a RadioGroup can be
accessed.
• A change in the state of any RadioButton inside a RadioGroup
triggers the CheckedChange event on the RadioGroup. Table 4.5
describes the event handling associated with a RadioGroup.
The onCheckedChange() event handler is called with two arguments as
depicted in Snippet 4.23.
The second argument to this callback method indicates the id of the
RadioButton that is checked.
ListView:
•One of the most common UI elements.
•To show a scrollable list of items on the screen wherein each item is
selectable.
•It is created using the <ListView> tag in the layout file as depicted in
Snippet 4.24.
The ListView can be populated in two ways:
•Either at compile time through a string array resource or
•Programmatically at runtime.
• Populating ListView at compile time with string array resource is pretty
straightforward.
• We just need to set android:entries attribute to refer to a string array resource (see Line
5 of Snippet 4.25). The string array resource is depicted in Snippet 4.26.
• To populate a ListView at runtime we need to use adapters.
• An adapter decouples the data and the ListView in which the data has to be
rendered.
• To achieve the decoupling, the adapter is first associated with the required
data and then it is attached to the ListView.
• As data changes, the adapter gets refreshed and eventually refreshes the
ListView.
• Snippet 4.27 depicts how to populate a ListView at runtime.
• In Snippet 4.27, we first access the ListView using the findViewById(int)
method (Line 1).
• Also, the string array resource used earlier (Snippet 4.26) is now accessed
via the getResources().
• getStringArray(int) method and assigned to a variable called nations, which
now acts as the data source for the ListView (Line 2).
• In Line 3 of Snippet 4.27, we create an adapter as reference to the
ListAdapter class.
• This adapter is instantiated using an object of ArrayAdapter.
• The constructor of ArrayAdapter in this case takes three parameters, viz.
context, layout, and array.
• The layout parameter specifies how the data obtained from the data source
(array) is to be displayed in the ListView.
• The array parameter specifies the data source for this adapter. Line 4 of
Snippet 4.27 shows how we can attach the adapter onto the ListView.
• Once the data is populated in the ListView, the user can perform various
actions on it.
• Typically, the user clicks on an item in the ListView.
• This generates an ItemClick event.
• The event handling related to ItemClick of a ListView is shown in Table
4.6.
The onItemClick() event handler gets invoked with four arguments:
•The ListView in which the item was clicked
•The row inside ListView that was clicked
•The position of the row that was clicked, and
•The id of the row that was clicked.
In Line 4 of Snippet 4.28, we have logged the position of the row clicked.
• ImageView is a container for image resources. It is created using the
<ImageView> tag.
• The src attribute resolves the location of the image that needs to be
rendered in ImageView, as depicted in Snippet 4.29.
An Image can also be rendered in the ImageView programmatically using
the setImage- Drawable(Drawable) method, as depicted in Snippet 4.30.
Dialog is a modal window displayed on the current Activity that
supports the user to perform small tasks related to the Activity in
focus.
• There are various types of dialogs that are supported in Android
such as
• AlertDialog,
• ProgressDialog,
• TimePickerDialog, and
• DatePickerDialog.
• An AlertDialog is created using a Builder class, as depicted in
Snippet 4.31.
MD-IV-CH-ppt.ppt
• The Builder class is an inner class of AlertDialog that is used to set the
layout and behavior of the dialog.
• We can observe that the Builder allows us to configure the title, message,
and buttons of the AlertDialog (Lines 2–15).
• An AlertDialog typically shows two buttons, positive and negative, to
collect response from the user.
• The Builder provides the setPositiveButton() and setNegativeButton()
methods to configure this (see Lines 4 and 10).
• We have to set listeners to monitor the user’s action on these buttons. In
Lines 7 and 13, the user is shown a message on click of any of the buttons
using a Toast
• Toast is an Android widget used to show unobtrusive messages to the user.
• It is created using the Toast class.
• To create a Toast message, we have to use the makeText() method that returns
a Toast object.
• The makeText() method accepts the following parameters –
• Context,
• Text to be displayed, and
• Duration for which the Toast has to be displayed.
• Toast is displayed to the user using the show()method.
LET’S APPLY: To create the SubscribeActivity for the 3CheersCable app
Having learnt how to create an Activity, prepare layouts for it, and add a
variety of UI components to it, let us now apply what we have learnt. In
this section,
• let us create the SubscribeActivity for the 3CheersCable app.
• This Activity allows the user to select the channel categories of his or
her choice to subscribe to.
• The selected channel categories are then displayed on a Confirm
subscription dialog window for user confirmation (see Fig. 4.11).
Figure 4.11 SubscribeActivity: (a) Subscribe Activity and (b) Confirm subscription
dialog window.
• For the sake of simplicity, let us break down the process involved in
creating this Activity into following simple steps, which are easy to
understand and follow:
• Step 1: Starting up:
• Create a new Android project titled 3CheersCable.
• Create a package com.app3c for the subscription module.
• Select the latest version of the Android platform available.
• Select the Create activity option in the New Android Application
wizard and name the Activity as SubscribeActivity.
Step 2: Setting up the layout resource
• Click Finish. We now have an Android project with a folder
structure similar to the HelloWorld app that we had created in
Chapter 2.
• Then Create a layout resource activity_subscribe.xml in the
reslayout folder.
• Set the argument passed to the setContentView() method as
R.layout. activity_subscribe in the SubscribeActivity.java file in
order to allow the Activity to use activity_subscribe.xml as its
layout resource.
Step 3: Adding UI components: Let us now add UI components to
the layout file (activity_subscribe.xml):
• Set <RelativeLayout> as the root element in
activity_subscribe.xml.
• Add TextView to this relative layout by dragging a TextView
component from the Form Widgets section of the Palette and
dropping it on the Graphical Layout editor. This TextView will
work as the title or the heading of this Activity.
• The following code is automatically generated in the
activity_subscribe.xml file.
1 <TextView
2 android:id=“@+id/textView1”
3 android:layout_width=“wrap_content”
4 android:layout_height=“wrap_content”
5 android:layout_alignParentLeft=“true”
6 android:layout_alignParentTop=“true”
7 android:text=“@string/subs_heading”>
8 </TextView>
• The TextView uses a string resource subs_heading whose value
has to be set as “Subscribe” in strings.xml.
• Similarly, add another TextView to provide instruction – “Select the channel
categories you wish to subscribe to”.
• Drag and drop a ListView from the Composite section of the Palette.
• This will generate the following code in the activity_subscribe.xml file.
1 <ListView
2 android:id=“@+id/listView1”
3 android:layout_width=“match_parent”
4 android:layout_height=“wrap_content”
5 android:layout_marginTop=“80dp”
6 android:layout_alignParentBottom=“true”>
7 </ListView>
• The layout_alignParentBottom attribute is set to true so that the
ListView does not hide the Button below it. This ListView will display
the list of channel categories that the user can subscribe from.
• Drag and drop a Button (Next) from the Form Widgets section onto
the Graphical Layout editor.
1 <Button
2 android:id=“@+id/button1”
3 android:layout_width=“wrap_content”
4 android:layout_height=“wrap_content”
5 android:layout_alignParentBottom=“true”
6 android:layout_alignRight=“@id/listView1”
7 android:layout_marginRight=“50dp”
8 android:text=“@string/subs_next”/>
• Step 4: Setting up the ListView: Let us now populate the ListView created in
the previous step:
• Create an ArrayAdapter in the onCreate() method that will be used to set the
ListAdapter for our ListView.
• The ArrayAdapter constructor takes the app context, the layout description of
each list item, and the list of objects to display in the ListView, as parameters.
1 ArrayAdapter<String> categoryListAdapter=new ArrayAdapter<String>(this,
android.R.layout. simple_list_item_ multiple_choice,category);
• The layout description used here is simple_list_item_multiple_choice.
• Use this description to add a checkbox to every list item, hence allowing
multiple selections.
• Create a method getCategoryNames() that will return a list of categories.
• This list is used to populate category (the third argument used in the constructor
of ArrayAdapter), which will insert these objects in the ListView.
1 public List<String> getCategoryNames(){
2 List<String> categoryNames=new ArrayList<String>();
3 categoryNames.add(“Movies”);
4 …
5 return categoryNames;
6 }
• These values are hardcoded in this specific exercise, but we shall learn how to
fetch these values dynamically through a Web service in Chapter 6.
• Insert the following lines of code in the onCreate() method to set the
adapter to the ListView and to enable multiple options in the list to
be selected.
1 ListView categoryList=(ListView) findViewById(R.id.listView1);
2 categoryList.setAdapter(categoryListAdapter);
3 categoryList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
• Step 5: Handling events: Let us handle the Click event on the Button
added earlier in the layout. On click of the Button, all the selected channel
categories will be displayed in the Confirm subscription dialog window.
• Create a reference for the Button in the onCreate() method.
1 Button next= (Button)findViewById(R.id.button1);
Register an onClickListener for the Button:
1 next.setOnClickListener(new OnClickListener() {
2 public void onClick(View v) {
3 // TODO Logic for the event handler goes here
4 }
5 });
• Get a list of all the selected items from categoryList.
• Use a SparseBooleanArray to store the position of the checked items.
• Add these items to an ArrayList that will be used to set up the ListView in
the dialog.
• Add this code to the onClick() callback method.
1 List<String> confirmed=new ArrayList<String>();
2 SparseBooleanArray sp=categoryList.getCheckedItemPositions();
3 for(int i=0;i<category.size();i++) {
4 if(sp.get(i)){
5 confirmed.add(category.get(i));}
• Step 6: Creating a dialog: Now let us create the dialog that appears on click
of the Next button.
• The dialog will have a ListView containing names of the selected channel
categories and two buttons to cancel or confirm the selection.
• Create a layout file subscribe_dialog in the layout folder. Add a ListView and
two Buttons to the layout.
• Create a new Dialog object by passing the current Activity as the context and
set the content
• view of the dialog using the subscribe_dialog layout. This code is written
within the onClick() callback method of SubscribeActivity.
1 subscribe_dialog=new Dialog(SubscribeActivity.this);
2 subscribe_dialog.setContentView(R.layout.subscribe_dialog);
Populate the ListView in the dialog using the confirmed ArrayList obtained
from the previous step:
1 ListView lv=(ListView)subscribe_dialog.findViewById(R.id.listView2);
2 ArrayAdapter<String> la=new
ArrayAdapter<String>(SubscribeActivity.this,
android.R.layout.simple_list_item_1,confirmed);
3 lv.setAdapter(la);
• Notice that we have used subscribe_dialog.findViewById() to obtain the
ListView. This is because the ListView here is a part of the dialog, and
not of the Activity.
• Set the title for the dialog and call the show() method of the dialog.
1 subscribe_dialog.setTitle(“Confirm subscription”);
2 subscribe_dialog.show();
INTERACTION AMONG ACTIVITIES
So far, we have seen how to create an Activity, define its makeup in
a layout file, followed by
• Arranging required UI elements in the layout, and
• Provide functionality to these elements to respond to user
actions.
• This discussion was only around a single Activity.
• However an app may comprise more than one Activity.
For example, an e-mail app typically has an Activity to list all the
messages and another one to display a selected message.
• In such scenarios, a user has to navigate and share data between Activities.
• This leads to the requirement for Activities not only to interact with each
other but also to send and receive information between them.
• Android provides this mechanism of navigating and sharing information
between Activities using Intent.
• Intent is a message-passing framework that is used to carry out interaction
between Activities and
• Also other Android building blocks such as Services and Broadcast
Receivers.
Let us now explore both the aspects of an Intent with respect to Activities –
• Navigation and
• Exchange of data between Activities
Navigating B:etween Activities:
• To navigate to an Activity from another Activity, we make use of
an Intent. It is a two-step process, as follows:
Step 1: Create an Intent object with two parameters, as depicted in
Line 1 of Snippet 4.32.
• The first parameter is context and the second parameter is the
second (next) Activity to navigate.
• Context is an object provided by Android runtime environment to
the app.
• It contains the global information about the environment in
which the app is running.
Step 2: Pass this Intent object to startActivity() method, as depicted
in Line 2 of Snippet 4.32.
• Every Android component needs to get registered in AndroidManifest.xml
after implementation.
• Therefore, we have to register the Activities created in an app in the
manifest file, as shown in Snippet 4.33.
Exchanging Data
• We can pass data as part of the Intent that can be retrieved by
the second (next) Activity.
• The simplest way to pass data between Activities is using a key–
value pair. We can pass data of types such as boolean, int, float,
char, String, arrays, and ArrayList using the key–value pairs.
• Line 2 of Snippet 4.34 shows adding of a boolean data to an
Intent object, before the next Activity is started.
• Data is added as key–value pair using the putExtra() method of
the Intent object.
• The putExtra() method accepts a String as the first parameter,
which is the key and the value corresponding to it as the second
parameter. In Snippet 4.34,
• key1 signifies the key and true signifies the value key1 holds.
The putExtra() method is overloaded and accepts primitive data types, arrays,
and ArrayList of these data types.
Another way of passing values is by creating an object of type Bundle.
It acts like a collection of key–value pairs that can be passed to another
Activity.
Line 2 of Snippet 4.35 shows creation of a Bundle object.
Lines 3–5 show addition of a collection of key–value pairs to the Bundle.
This Bundle is added to an Intent object, before the next Activity is started
(Line 6).
• Now, to retrieve data in the next Activity (at the receiving end), we need to
get an instance of the Intent passed from the first Activity.
• This is achieved using the getIntent()method. From the Intent object, we have
to retrieve the key–value pair either directly (see Snippet 4.36) or from the
Bundle object (see Snippet 4.37).
MD-IV-CH-ppt.ppt
• The first parameter is the key that was passed while sending the data.
• The second parameter is the default value that must be assigned to the variable in
case the key–value pair corresponding to the supplied key is unavailable in the
Intent.
• In Line 2 of Snippet 4.37, the Bundle that was sent earlier (refer to Snippet 4.35)
is retrieved using the getExtras() method.
• One of the key–value pairs is retrieved from the Bundle object using the get-
Boolean() method, which accepts the key as the first parameter and default value
as the second.
MD-IV-CH-ppt.ppt
• In Snippets 4.36 and 4.37, the getIntent()
method is used to retrieve the Intent that
started
• the component. In Line 2 of Snippet 4.36,
the boolean data that was sent earlier
directly using the
• putExtra() method (refer to Snippet 4.34)
is retrieved using the getBooleanExtra()
method.
FRAGMENTS
• With the advent of tablets in market, developers got more real
estate for an app UI.
• Fragments have been introduced to cater to leverage the larger
UIs since the advent of Android 3.0 (Honeycomb – API level 11).
• Fragments are UI modules and are similar to Activities in many
ways.
• Fragments allow the flexibility of designing the UI such that in a
single screen it is possible to accommodate more than one UI
modules.
• In such a scenario, typically, Activity acts as a container and
hosts multiple Fragments to be shown on a single screen.
• shows the corresponding states.
• Figure 4.13 depicts two Fragments hosted within an Activity.
• Fragment on the left shows a list of nations and that on the right shows the
corresponding states.
MD-IV-CH-ppt.ppt
Building Fragments
Building Fragments of an app can be broadly categorized into three
steps:
• Designing the Fragment layout,
• Creating Fragment class, and
• Associating Fragment to an Activity.
Let us now try to understand these steps with an example that will
help in achieving the result as depicted in Fig. 4.13.
• To start with, we have to design the layout of the Fragment in the
associated layout XML file.
• As in the example, we have two Fragments:
• Nation Fragment and
• State Fragment.
• We need to define two layout files:
• nation_fragment.xml and
• state_fragment.xml (see Snippets 4.38 and 4.39, respectively).
MD-IV-CH-ppt.ppt
MD-IV-CH-ppt.ppt
• The next step is to create a class that extends Fragment (or its subclasses).
• This class is required to inflate the Fragment layout and define the behavior
of Fragment. Because we have two Fragments, we need to define two
Fragment classes:
• NationFragment and
• StateFragment (see Snippets 4.40 and 4.41,respectively).
MD-IV-CH-ppt.ppt
MD-IV-CH-ppt.ppt
• In Snippets 4.40 and 4.41, we override the onCreateView() method.
• This is one of the life-cycle methods of a Fragment and is used to instantiate the
UI of the Fragment.
• This method returns a View object, which is the UI of the Fragment, created
using the inflate() method of the LayoutInflater class (Lines 5 and 6).
• The inflate() method inflates(fill) the Fragment’s UI (defined in the Fragment
layout file and passed as the first argument here), and then attaches it to the
designated container in the host Activity (passed as the second argument here).
• The concluding step is to associate the Fragment(s) to the anchor Activity
(MainActivity here). This can be achieved either statically or dynamically.
• To associate the Fragment to an Activity in a static manner, we need to add
the <fragment> tag in the layout file of the host Activity (see Snippet 4.42).
• The <fragment> tag defines the designated container for Fragments, and
has most attributes similar to other UI elements in Android.
• The most important attribute of the <fragment> tag is android:name that
defines the Fragment class to be loaded in the designated container.
• As depicted in Lines 10 and 23, the value for android:name attribute is the
Fragment class created earlier (NationFragment and StateFragment).
• No changes need to be made in the Activity class, and as soon as the
Activity is rendered, both Fragments are attached to it and we get the result
as shown earlier in Fig. 4.13.
MD-IV-CH-ppt.ppt
MD-IV-CH-ppt.ppt
• Alternatively, Fragments can be dynamically associated with an Activity
using placeholders for them in the layout file of the Activity. Here, this is
done using <FrameLayout> tag as shown in Snippet 4.43.
MD-IV-CH-ppt.ppt
• In the onResume() method of the Activity, we attach the required
Fragments at runtime using the FragmentManager API (See Snippet 4.44).
• In Line 1, an object of FragmentTransaction is obtained from the
beginTransaction() method of the FragmentManager class.
• FragmentTransaction is used to perform transactions such as
• add,
• replace, or
• remove on Fragments dynamically.
• Lines 2 and 3 depict the addition of the Fragments to the Activity using the
add() method of the FragmentTransaction class.
The add() method accepts the following parameters –
• id of the placeholder for the Fragment,
• instance of the Fragment, and
• a tag with which the Fragment can be referred later, if need be.
The commit() method used in Line 4 is the most important line in
Snippet 4.44. It commits the transactions performed on the
Fragments.
MD-IV-CH-ppt.ppt
• Till now, we have seen how to design a Fragment layout, create a Fragment
class, and associate a Fragment to an Activity. Working with Fragments
requires us to further understand its life cycle and how they interact with
each other.
• Let us now explore these two critical aspects in the next two subsections.
Life Cycle of Fragments
• Similar to an Activity, Fragment too has its own life cycle.
Because Fragment is attached to an Activity, the life cycle of a
Fragment is intertwined with the Activity.
• This results in interlacing of the life-cycle methods of Activity
and Fragment.
• The Fragment life cycle starts with a call to onAttach() method
when a Fragment is added to an Activity.
• The next call is to the method onCreate() that is used for
initializing instance variables of the Fragment.
• onCreateView() method follows onCreate() method to instantiate
the UI of the Fragment, as seen earlier in Snippets 4.39 and 4.40.
• In this method, we inflate the XML layout file that describes the UI of the
Fragment. This is followed by call to the onActivityCreated() method,
which is invoked when the host Activity of this Fragment has completed
execution of its own onCreate() method.
• onStart() is the next method that is invoked when the Fragment becomes
visible.
• The last method that is called before the Fragment becomes active is
onResume(), which enables the user to interact with the Fragment.
• When the Fragment transitions from the active to destroyed state, it goes
through onPause(), onStop(), onDestroyView(), onDestroy(), and
onDetach() callbacks.
• The main difference between the life cycle of an Activity and that of a
Fragment is that ----
• The Activity life cycle is managed by Android runtime using task stack
(refer Section 4.2.1),
• Whereas Fragments are managed by the host Activity using back stack
mechanism.
• The back stack mechanism helps developer to manage multiple Fragment
transactions in an Activity.
Interaction Between Fragments
• Referring to Fig. 4.13, if a user selects another nation, the second
Fragment has to be populated with the respective states.
• To achieve this, two Fragments have to interact with each other.
• In this example, as a single Activity hosts two Fragments, the
interaction can be achieved as explained below.
• To start with, the NationFragment.java (refer to Snippet 4.40)
has to be modified as depicted in Lines 7–12 of Snippet 4.45.
MD-IV-CH-ppt.ppt
• In Line 7 of Snippet 4.45, we access the ListView in the Fragment that
displays the list of nations.
• In Line 8, we set an OnItemClickListener on the ListView.
• The logic inside the onItemClick() handler determines the country clicked
by the user and passes that as a parameter to the onFragmentAction()
method.
• The onFragmentAction() is a user-defined method in the MainActivity
class that passes on the selected country to the StateFragment so that the
StateFragment can modify the list it is displaying.
• The logic of onFragmentAction() method is as shown in Snippet 4.46.
MD-IV-CH-ppt.ppt
• In the onFragmentAction() method, an instance of FragmentManager is
obtained as shown in Line 2 of Snippet 4.46.
• The obtained instance is further used to access the StateFragment.
• The findFragmentByTag() method takes a String variable as parameter and
returns the Fragment identified by the tag supplied.
• In Line 4, the setList(), a user-defined method of StateFragment is invoked
with the country selected by the user as argument.
• The definition of setList() method is as shown below in Snippet 4.47.
MD-IV-CH-ppt.ppt
• The setList() method in Snippet 4.47 accepts the country selected by the
user.
• On the basis of this selection, it populates the required states into states
array (see Lines 5 – 11).
• The states array is further used in Line 12 to set the adapter of the
ListView, thereby ensuring that when a nation is selected in the
NationFragment, its corresponding states are displayed in the
StateFragment.
ACTION BAR
• An action bar is a dedicated functional strip on top of the screen
that provides exclusive space for displaying varieties of global
functionality required in an app such as navigation tabs, search,
and user settings.
• It is up to the developer to populate action bar with more
functionalities that deemed fit to be accessed across the app.
• Figure 4.17 shows a typical action bar. Android runtime
automatically manages its placement based on the device screen
size and orientation.
• As shown in the figure, an action bar typically consists of the
following elements:
1. App branding (icon and name).
2. Navigation tabs that provide a better way of navigating between
the Fragments in a single Activity.
3. Action items such as zoom in and zoom out; Action views such as
search in this example that provide a mechanism for the user to
perform common functionalities inside an app.
4. Overflow button that holds extra menu options that are not
visible by default in an action bar. The extra options surface up
when the overflow button is tapped.
MD-IV-CH-ppt.ppt
• Having understood the basic layout of the action bar, let us now implement
the action bar.
• An action bar is available by default in any app, and it contains the app
icon and name.
• This is because android:theme attribute in <application> tag is set to
Theme.Holo, as shown in Snippet 4.48.
• Action bar can be removed by setting the value of android:theme to
Theme.NoTitleBar.
MD-IV-CH-ppt.ppt
• Themes are used to maintain consistent look and feel across the app.
• Theme.Holo is the default theme in Android Jelly Bean.
• We can further populate the action bar with navigation tabs, action views,
action items, and overflow button.
MD-IV-CH-ppt.ppt
MD-IV-CH-ppt.ppt
MD-IV-CH-ppt.ppt
• Navigation tabs provide a way of switching between multiple Fragments in
the same Activity.
• Snippet 4.49 depicts how navigation tabs are implemented in an action bar.
In Line 7 of Snippet 4.49, we get an instance of ActionBar using the
getActionBar() method.
• To enable the action bar to display navigation tabs, we use the
setNavigationMode() method of the ActionBar as shown in Line 8.
• The ActionBar.NAVIGATION_MODE_TABS constant is supplied as a
parameter to the setNavigationMode() method to make the action items
appear as tabs in the action bar.
• In Lines 9–11, we create three tabs using the newTab() method.
• Additionally, we also set the text to be displayed on the tab (using the
setText() method) and the listener to be triggered when a user selects the
tab (using the setTabListener() method).
• When we pass this as a parameter to the setTabListener(), it means that the
Activity is going to implement the event handler to handle the user action
on the tab.
• This is another way of achieving event handling in Android unlike what we
have already learnt in Section 4.4.2 of this chapter.
• In Lines 12–14, we use the addTab() method to add the tabs created in
Lines 9–11 to the action bar.
• The layout of this Activity contains a FrameLayout with id
fragmentContent. This is the container for Fragments in this Activity.
• In the onTabSelected() method (Lines 17–35), we obtain the position of the
selected tab and replace the Fragment in the container based on the user
selection.
• Fragment1, Fragment2, and Fragment3 are three Fragments, each
containing a TextView. The layouts of these Fragments have been
designed, and the classes for these have been created just like how we did
earlier in Section 4.8.1 of this chapter.
• In Line 34, the replace() method of FragmentTransaction is called to
replace an existing Fragment in the container with a new one.
• Action views and items provide a mechanism for the user to perform
common functionalities inside an app.
• To create them in the action bar of an app, we first have to declare a menu
resource.
• Menu resources are located in the resmenu folder in the project structure of
the app.
• To create a menu resource XML file, right click on menu folder, select New
→ Android XML File, and provide the appropriate values in the New
Android XML File wizard (shown earlier in Fig. 4.9).
• Editing of this XML file can be done using either a visual XML file editor
or a simple text-based editor. Snippet 4.50 shows the definition of the menu
XML file.
MD-IV-CH-ppt.ppt
MD-IV-CH-ppt.ppt
Value Description
ifRoom
Only place this item in the app bar if there is room for it.
If there is not room for all the items marked "ifRoom", the
items with the lowest orderInCategory values are displayed
as actions, and the remaining items are displayed in the
overflow menu.
withText
Also include the title text (defined by android:title) with the
action item. You can include this value along with one of the
others as a flag set, by separating them with a pipe |.
• android:orderInCategory is an integer attribute that dictates the order in
which the menu items will appear within the menu when it is displayed.
• Menu items in ToolBar are arranged from left to right (or start to end in
RTL mode) in the ascending order (i.e. 1,2,3 -> left to right)
never Never place this item in the app bar. Instead, list the item in
the app bar's overflow menu.
always Always place this item in the app bar. Avoid using this unless
it's critical that the item always appear in the action bar.
Setting multiple items to always appear as action items can
result in them overlapping with other UI in the app bar.
collapseActi
onView
The action view associated with this action item is collapsible.
(as declared
by android:actionLayout or android:actionViewClass)
Introduced in API Level 14.
• In Snippet 4.50, the menu contains a total of five items. The first item
(Lines 3–7) and second item (Lines 8–12) represent the zoom-in and zoom-
out buttons (see Fig. 4.17).
• These items have android:icon, android:title, and android:showAsAction
attributes among other attributes.
• The android: icon attribute is used to set an icon to the menu item when it is
being displayed.
• The value of the android:title attribute is the text that is displayed in the
action bar (in this case “Zoom In” and “Zoom Out”).
• The value of the android:showAsAction attribute determines when and how
the item is shown in the action bar.
• The fourth and fifth items (Lines 19–22 and 23–25) do not specify the
android:showAsAction attribute.
• This results in the appearance of the overflow button on the action bar.
• These menu items are displayed only when the user taps on the overflow
button in the action bar.
• The third item (Lines 13–18) represents a specialized widget in Android
called the SearchView.
• The SearchView is used to add querying functionality in an app.
• The android:actionViewClass attribute defines the look and feel of the
widget on the action bar.
• Once the menu resource is designed, we need to inflate it in the Activity
class using the onCreate-OptionsMenu() method, as shown in Snippet 4.51.
Layout Attributes
• android:id
This is the ID which uniquely identifies the view.
• UI element is identified using this unique id.
• @+id/id_name is used to set the id.
• android:layout_width
This is the width of the layout.
• android:layout_height
This is the height of the layout
• android:layout_marginTop
This is the extra space on the top side of the layout.
• android:layout_marginBottom
This is the extra space on the bottom side of the layout.
• android:layout_marginLeft
This is the extra space on the left side of the layout.
• android:layout_gravity
This specifies how child Views are positioned.
• android:layout_weight
This specifies how much of the extra space in the layout should be
allocated to the View.
• android:layout_x
This specifies the x-coordinate of the layout.
• android:layout_y
This specifies the y-coordinate of the layout.
• android:layout_width
This is the width of the layout.
• android:paddingLeft
This is the left padding filled for the layout.
• android:paddingRight
This is the right padding filled for the layout.
• android:paddingTop
This is the top padding filled for the layout.
• android:paddingBottom
This is the bottom padding filled for the layout.
MD-IV-CH-ppt.ppt
• Two ways to adapt to changes in orientation :
Anchoring, and
resizing and repositioning.
• Using different XML files for different orientations:
Use the layout folder for portrait UI, and
layout-land for landscape UI.
• Three ways to persist activity state:
Use the onPause() method.
Use the onSaveInstanceState() method.
Use the onRetainNonConfigurationInstance() method.
• Getting the dimension of the current device: Use the
WindowManager class’s getDefaultDisplay() method.
• Constraining the activity’s orientation:
Use the setRequestOrientation() method or the
android:screenOrientation attribute in the
AndroidManifest.xml file.
• Action Bar :Replaces the traditional title bar for older versions of
Android.
• Action items: Action items are displayed on the right of the
Action Bar. They are created just like options menus.
• Application icon :Usually used to return to the “home” activity of
an application. It is advisable to use the Intent object with the
Intent.FLAG_ACTIVITY_CLEAR_TOP flag.
View Identification
•A view object may have a unique ID assigned to it which will identify the
View uniquely within the tree.
The syntax for an ID, inside an XML tag is −
android:id="@+id/my_button"
•Following is a brief description of @ and + signs
•The at-symbol (@) at the beginning of the string indicates that the XML
parser should parse and expand the rest of the ID string and identify it as an ID
resource.
•The plus-symbol (+) means that this is a new resource name that must be
created and added to our resources.
•To create an instance of the view object and capture it from the layout, use the
following:
MD-IV-CH-ppt.ppt
MD-IV-CH-ppt.ppt

More Related Content

PPT
Android lifecycle
PPTX
Unit-1.2 Android-Activities, Fragments, and Intents (1).pptx
PPTX
Data Transfer between activities and Database
PDF
MAD Unit - 2 Activity and Fragment Management in Android (Diploma IT)
PDF
Introduction to Andriod Studio Lecture note: Android Development Lecture 1.pdf
PPT
Unit 2 in environment science and technology
PDF
Native Android Development Practices
PPTX
11.11.2020 - Unit 5-3 ACTIVITY, MENU AND SQLITE DATABASE.pptx
Android lifecycle
Unit-1.2 Android-Activities, Fragments, and Intents (1).pptx
Data Transfer between activities and Database
MAD Unit - 2 Activity and Fragment Management in Android (Diploma IT)
Introduction to Andriod Studio Lecture note: Android Development Lecture 1.pdf
Unit 2 in environment science and technology
Native Android Development Practices
11.11.2020 - Unit 5-3 ACTIVITY, MENU AND SQLITE DATABASE.pptx

Similar to MD-IV-CH-ppt.ppt (20)

PDF
ODP
Anatomy of android application
PPTX
iOS app dev Training - Session1
PPTX
App Fundamentals and Activity life cycle.pptx
PPTX
Unit 5 Activity and Activity Life Cycle.pptx
PPTX
Kotlin for Android App Development Presentation
DOCX
Using intents in android
PPTX
Modul 2.pptxhelllojobbigtufytfythjgjhbknkjlnlk
PDF
android_mod_3.useful for bca students for their last sem
KEY
Android Workshop
DOCX
Android building blocks and application life cycle-chapter3
PPT
PPT
Android Training Ahmedabad , Android Course Ahmedabad, Android architecture
PDF
Android Activities.pdf
PDF
Android Jumpstart Jfokus
PPTX
02. Android application development_Lec2.pptx
PDF
Android application development
PDF
Android studio
PPT
Part 2 android application development 101
PPTX
Android Development Basics
Anatomy of android application
iOS app dev Training - Session1
App Fundamentals and Activity life cycle.pptx
Unit 5 Activity and Activity Life Cycle.pptx
Kotlin for Android App Development Presentation
Using intents in android
Modul 2.pptxhelllojobbigtufytfythjgjhbknkjlnlk
android_mod_3.useful for bca students for their last sem
Android Workshop
Android building blocks and application life cycle-chapter3
Android Training Ahmedabad , Android Course Ahmedabad, Android architecture
Android Activities.pdf
Android Jumpstart Jfokus
02. Android application development_Lec2.pptx
Android application development
Android studio
Part 2 android application development 101
Android Development Basics
Ad

More from bharatt7 (7)

PPTX
Phase_1_ppt.pptx
PPTX
phase 2 ppt.pptx
PPTX
phase 1 ppt dal adulteration.pptx
PPT
MD-III-CH-ppt.ppt
PPTX
Eswar Technical Seminar ppt.pptx
PPT
MD-I-CH-ppt.ppt
PPTX
Space-based solar power.pptx
Phase_1_ppt.pptx
phase 2 ppt.pptx
phase 1 ppt dal adulteration.pptx
MD-III-CH-ppt.ppt
Eswar Technical Seminar ppt.pptx
MD-I-CH-ppt.ppt
Space-based solar power.pptx
Ad

Recently uploaded (20)

PPTX
UNIT 4 Total Quality Management .pptx
PDF
Soil Improvement Techniques Note - Rabbi
PPTX
communication and presentation skills 01
PDF
COURSE DESCRIPTOR OF SURVEYING R24 SYLLABUS
PPTX
Safety Seminar civil to be ensured for safe working.
PPTX
Information Storage and Retrieval Techniques Unit III
PDF
SMART SIGNAL TIMING FOR URBAN INTERSECTIONS USING REAL-TIME VEHICLE DETECTI...
PPTX
CURRICULAM DESIGN engineering FOR CSE 2025.pptx
PDF
Integrating Fractal Dimension and Time Series Analysis for Optimized Hyperspe...
PDF
A SYSTEMATIC REVIEW OF APPLICATIONS IN FRAUD DETECTION
PDF
Level 2 – IBM Data and AI Fundamentals (1)_v1.1.PDF
PDF
UNIT no 1 INTRODUCTION TO DBMS NOTES.pdf
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PDF
86236642-Electric-Loco-Shed.pdf jfkduklg
PDF
R24 SURVEYING LAB MANUAL for civil enggi
PDF
Unit I ESSENTIAL OF DIGITAL MARKETING.pdf
PDF
BIO-INSPIRED ARCHITECTURE FOR PARSIMONIOUS CONVERSATIONAL INTELLIGENCE : THE ...
PDF
Categorization of Factors Affecting Classification Algorithms Selection
PDF
Exploratory_Data_Analysis_Fundamentals.pdf
UNIT 4 Total Quality Management .pptx
Soil Improvement Techniques Note - Rabbi
communication and presentation skills 01
COURSE DESCRIPTOR OF SURVEYING R24 SYLLABUS
Safety Seminar civil to be ensured for safe working.
Information Storage and Retrieval Techniques Unit III
SMART SIGNAL TIMING FOR URBAN INTERSECTIONS USING REAL-TIME VEHICLE DETECTI...
CURRICULAM DESIGN engineering FOR CSE 2025.pptx
Integrating Fractal Dimension and Time Series Analysis for Optimized Hyperspe...
A SYSTEMATIC REVIEW OF APPLICATIONS IN FRAUD DETECTION
Level 2 – IBM Data and AI Fundamentals (1)_v1.1.PDF
UNIT no 1 INTRODUCTION TO DBMS NOTES.pdf
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
86236642-Electric-Loco-Shed.pdf jfkduklg
R24 SURVEYING LAB MANUAL for civil enggi
Unit I ESSENTIAL OF DIGITAL MARKETING.pdf
BIO-INSPIRED ARCHITECTURE FOR PARSIMONIOUS CONVERSATIONAL INTELLIGENCE : THE ...
Categorization of Factors Affecting Classification Algorithms Selection
Exploratory_Data_Analysis_Fundamentals.pdf

MD-IV-CH-ppt.ppt

  • 2. Chapter 4: App User Interface LEARNING OBJECTIVES After completing this chapter, you will be able to: • Create basic user interface of Android app. • Illustrate Activity life cycle. • Devise interaction among Activities using Intents. • Compose tablet UI using Fragments and action bar.
  • 3. This chapter primarily focuses on user interface aspects of an app that contribute to a rich user experience. • It starts with the core building block of Android UI – Activity – and further delves into layouts and other UI elements that are required for designing the screen makeup.
  • 4. Activity • An activity represents a single screen with a user interface just like window or frame of java. Android activity is the subclass of ContextThemeWrapper class. • An activity is a window that contains the user interface of your applications. • An application can have zero or more activities. Typically, applications have one or more activities, and the main aim of an activity is to interact with the user. From the moment • When the user taps on an app icon, the designated Activity gets launched into the foreground where it has the user focus. Pressing the Back key destroys the Activity in focus (current Activity) and displays the previous Activity to the user. Pressing the Home key moves the Activity in focus to the background, navigating to the Home screen.
  • 5. [[References] • package android.view; • import android.content.Context; • import android.content.ContextWrapper; • import android.content.res.Resources; • /** • * A ContextWrapper that allows you to modify the theme from what is in the wrapped context. • */ • public class ContextThemeWrapper extends ContextWrapper { • private Context mBase; • private int mThemeResource; • private Resources.Theme mTheme; • private LayoutInflater mInflater; • public ContextThemeWrapper() { • super(null); • } • • public ContextThemeWrapper(Context base, int themeres) { • super(base); • mBase = base; • mThemeResource = themeres;
  • 6. • From the moment an activity appears on the screen to the moment it is hidden, it goes through a number of stages. • These stages are known as an activity’s life cycle.
  • 7. One has to understanding the life cycle of an activity is vital to ensuring that your application works correctly. To create an activity, you create a Java class that extends the Activity base class: 1 package com.mad.firstapp; 2 import android.os.Bundle; 3 import android.app.Activity; 4 import android.view.Menu; 5 public class MainActivity extends Activity { 6 @Override 7 protected void onCreate(Bundle savedInstanceState) { 8 super.onCreate(savedInstanceState); 9 setContentView(R.layout.activity_main); 10 } 11 ... 12 }
  • 8. [[References] • The savedInstanceState is a reference to a Bundle object that is passed into the onCreate method of every Android Activity. Activities have the ability, under special circumstances, to restore themselves to a previous state using the data stored in this bundle. • onCreate is used to start an activity. super is used to call the parent class constructor. setContentView is used to set the xml. • protected because logically it should not be accessed by other class different from Activities. ... The onClick is public because it could be set or handled by external classes that not necessary are your Activity. ]
  • 9. [[References] onCreate(Bundle savedInstanceState) Function in Android: • When an Activity first call or launched then onCreate(Bundle savedInstanceState) method is responsible to create the activity. • When ever orientation(i.e. from horizontal to vertical or vertical to horizontal) of activity gets changed or when an Activity gets forcefully terminated by any Operating System then savedInstanceState i.e. object of Bundle Class will save the state of an Activity. • After Orientation changed then onCreate(Bundle savedInstanceState) will call and recreate the activity and load all data from savedInstanceState.]
  • 10. • [[References] • Basically Bundle class is used to stored the data of activity whenever above condition occur in app. • onCreate() is not required for apps. But the reason it is used in app is because that method is the best place to put initialization code. • You could also put your initialization code in onStart() or onResume() and when you app will load first, it will work same as in onCreate().]
  • 11. • Your activity class loads its user interface (UI) component using the XML file defined in your res/layout folder. • In this example, you would load the UI from the main.xml file: • setContentView(R.layout.activity_main);
  • 13. • [[References] • This is the XML optional preamble. version="1.0" means that this is the XML standard. This file conforms to. encoding="utf-8" means that the file is encoded using the UTF-8 Unicode encoding. • The encoding declaration If no encoding declaration exists in a document's XML declaration, that XML document is required to use either UTF-8 or UTF-16 encoding. • UTF stands for UCS Transformation Format, and UCS itself means Universal Character Set. The number 8 or 16 refers to the number of bits used to represent a character. They are either 8(1 to 4 bytes) or 16(2 or 4 bytes). • For the documents without encoding information, UTF-8 is set by default.]
  • 14. • 1 <?xml version=“1.0” encoding=”utf-8”?> • 2 <manifest • xmlns:android=“http://schemas.android.com/apk/res/android” • 3 package=“com.mad.firstapp” • 4 android:versionCode=“1” • 5 android:versionName=“1.0”> • 6 • 7 <uses-sdk • 8 android:minSdkVersion=“8” • 9 android:targetSdkVersion=“18”/> • 10 • 11 <application • 12 android:allowBackup=“true” • 13 android:icon=“@drawable/ic_launcher” • 14 android:label=“@string/app_name” • 15 android:theme=“@style/AppTheme” >
  • 15. 16 <activity 17 android:name=“com.mad.firstapp.MainActivity” 18 android:label=“@string/app_name”> 19 <intent-filter> 20 <action android:name=“android.intent.action.MAIN”/> 21 22 <category android:name=“android.intent.category.LAUNCHER”/> 23 </intent-filter> 24 </activity> 25 </application> 26 27 </manifest> Snippet 2.5 AndroidManifest.xml.
  • 16. [[References] xmlns:android=“http://schemas.android.com/apk/res/android” In XML, xmlns declares a Namespace. In fact, when you do: • <LinearLayout android:id> • </LinearLayout> • Instead of calling android:id, the xml will use http://schemas.android.com/apk/res/android:id to be unique. Generally this page doesn't exist (it's a URI, not a URL), but sometimes it is a URL that explains the used namespace. • The namespace has pretty much the same uses as the package name in a Java application. • Here is an explanation. • Uniform Resource Identifier (URI) • A Uniform Resource Identifier (URI) is a string of characters which identifies an Internet Resource. • The most common URI is the Uniform Resource Locator (URL) which identifies an Internet domain address. • Another, not so common type of URI is the Universal Resource Name (URN). • ]
  • 17. [[References] 12 android:allowBackup=“true” The allowBackup attribute determines if an application's data can be backed up and restored, By default, this flag is set to true. When this flag is set to true, application data can be backed up and restored by the user using adb backup and adb restore. • This may have security consequences for an application. • adb backup allows users who have enabled USB debugging to copy application data off of the device. • Once backed up, all application data can be read by the user. • adb restore allows creation of application data from a source specified by the user. • Cont…..
  • 18. Following a restore, applications should not assume that the data, file permissions, and directory permissions were created by the application itself. Setting allowBackup="false" opts an application out of both backup and restore. To fix this warning, decide whether your application should support backup and explicitly set android:allowBackup=(true|false) ]]
  • 19. [[References] Android Intent android:name=“android.intent.action.MAIN”/> • Android Intent is the message that is passed between components such as activities, content providers, broadcast receivers, services etc. It . • android. intent. action. MAIN means that this activity is the entry point of the application, i.e. when you launch the application, this activity is created • Main is action intent and Launcher is category of the intent. Main tells operating system that the activity is main activity of the application, Launcher tells the operating system that the activity should be visible in the launcher of the phone. • android:name=“android.intent.category.LAUNCHER”/> ]
  • 20. Summary: Key points about this file are as below: • It defines the package name of the application as “com.mad.firstapp” • The version code of the application is 1. This value is used to identify the version number of your application. It can be used to programmatically determine whether an application needs to be upgraded. • The version name of the application is 1.0. This string value is mainly used for display to the user. • The application uses the image named ic_launcher.png located in the drawable folder. • The name of this application is the string named app_name defined in the strings.xml file.
  • 21. • There is one activity in the application represented by the MainActivity.java file. The label displayed for this activity is the same as the application name. • Within the definition for this activity, there is an element named <intent- filter>: • The action for the intent filter is named android.intent.action.MAIN to indicate that this activity serves as the entry point for the application. • The category for the intent-filter is named android.intent.category.LAUNCHER to indicate that the application can be launched from the device’s Launcher icon. • Finally, the android:minSdkVersion attribute of the <uses-sdk> element specifies the minimum version of the OS on which the application will run.
  • 22. The Activity base class defines a series of events that govern the life cycle of an activity. Figure 3-1 shows the lifecycle of an Activity.
  • 23. The Activity class defines the following events: • onCreate()—Called when the activity is first created • onStart()—Called when the activity becomes visible to the user • onResume()—Called when the activity starts interacting with the user • onPause()—Called when the current activity is being paused and the previous activity is being resumed • onStop()—Called when the activity is no longer visible to the user • onDestroy()—Called before the activity is destroyed by the system (either manually or by the system to conserve memory) • onRestart()—Called when the activity has been stopped and is restarting again
  • 24. • By default, the activity created for you contains the onCreate() event. Within this event handler is the code that helps to display the UI elements of your screen.
  • 25. Understanding Life Cycle of an Activity using an Example Let us now explore these life-cycle methods using Snippet 4.1. All six life- cycle methods are overridden, and • In each method a log statement – Log.i (String tagname, String message) – has been placed to reflect the life-cycle method and state, as transition happens. • The log messages are displayed in the LogCat utility in Dalvik Debug Monitor Server (DDMS).
  • 31. When we run Snippet 4.1 and observe the LogCat, • we see that three life-cycle methods (onCreate, onStart, and onResume) • Get executed as soon as the app is launched, as shown in Fig. 4.2. Figure 4.2 LogCat view depicting methods execution on app launch.
  • 32. The first method to get executed is onCreate(). • This is executed only once during the lifetime of an Activity, that is, at the beginning, when the Activity is launched. • If we have any instance variables in the Activity, the initialization of those variables can be done in this method. After onCreate(), the onStart() method is executed. • During the execution of onStart(), the Activity is not yet rendered on screen but is about to become visible to the user. • In this method, we can perform any operation related to UI components. • When the Activity finally gets rendered on the screen, onResume() is invoked. • At this point, the Activity is in the active state and is interacting with the user.
  • 33. • If the Activity loses its focus and is only partially visible to the user, it enters the paused state. During • this transition, the onPause() method is invoked. In the onPause() method, we may commit database • transactions or perform light-weight processing before the Activity goes to the background. • When the Activity comes back to focus from the paused state, onResume() is invoked. This transition • between paused and active states is a frequent phenomenon, thus onResume() is called more often than • any other life-cycle method of an Activity. Because of this reason, it is advisable to keep the implementation • of onResume() as light as possible.
  • 34. • From the active state, if we hit the Home key, the Activity goes to the background and the Home screen • of the device is made visible. During this event, the Activity enters the stopped state. Both onPause() and • onStop() methods are executed, as shown in Fig. 4.3.
  • 35. • When we reopen the app,[1] we observe that the Activity is now transitioning from the stopped state to the active state. • This is characterized by invocation of only onStart() and onResume() methods (see Fig. 4.4), • Validating that onCreate() gets invoked only once in a lifetime of the Activity. Note: Either by tapping the app icon or by long pressing of Home key and selecting the running app
  • 36. • To destroy the Activity on the screen, we can hit the Back key. This moves the Activity into the destroyed state. • During this event, onPause(), onStop(), and onDestroy() methods are invoked, as shown in Fig. 4.5. • You may recall that, in the destroyed state, the Android runtime marks the Activity to become eligible to go out of memory.
  • 37. To summarize, the Activity is alive from onCreate() to onStop() methods and depending upon how many times the Activity goes to the background or loses focus and comes back to the foreground, onStart(), onResume(), onPause(), and onStop() methods get executed. When an Activity is destroyed, the onDestroy() method is called. Once an Activity is destroyed, it has to be recreated to return to the active state.
  • 38. • As there may be a flurry of messages that may get generated in LogCat, it would be convenient to filter the app-specific log messages. • To add a new filter, click on + sign of the Saved Filters view, as depicted in Fig. 4.6. This will open the Logcat Message Filter Settings dialog box, as depicted in Fig. 4.7.
  • 39. • Enter a relevant name in the Filter Name field (Fig. 4.7). This name will appear in the Saved Filters view,as depicted in Fig. 4.8. • The LogCat message can be filtered in various ways, but we are using filter by LogTag. • Enter the tagname parameter (refer to Snippet 4.1) of Log.i()[2] in the by Log Tag field, as depicted in Fig. 4.7. • Select info in by Log Level drop-down; this corresponds to the log level selected in Snippet 4.1. • Click OK in the Logcat Message Filter Settings dialog box to save the filter, as depicted in Fig. 4.8. Note: [2] i in Log.i stands for info.
  • 40. The LogCat outputs shown in Figs. 4.2–4.5 were captured after applying the filter. Having understood the core programming component of UI (Activity), its states and life-cycle methods
  • 41. UI RESOURCES • User interface resources are typically the nonprogramming components of UI that help a developer in laying out the visual structure of screens, along with string constants and images that populate these screens. • There are other UI resources such as menu that provide different ways of user interaction and navigation in apps. UI Resources are • Layout Resources • String Resources • Image Resources
  • 42. Layout Resources • Layout resource provides a visual blueprint for an Activity and defines how the UI elements in a screen is arranged. • Layout resources are XML files located in the reslayout folder. • A layout file may be associated with one or more Activities. • You may recall the setContentView(R.layout.activity_main) Method that associates an Activity with a layout file (activity_main.xml).
  • 43. • Upon creating a layout resource, Android framework generates a unique id for it in the R.java file present in the gen folder. • The R.java file contains information about all nonprogramming components, using which a developer can resolve these resources inside programming components. For example, if a layout file is named activity_main.xml, it is represented as an integer constant – public static final int activity_main – in the R.java file under a static class – layout. This is applicable to all nonprogramming components.
  • 44. [[References-two slides about R.java file] • gen — Contains the R.java file, a compiler-generated file that references all the resources found in your project. You should not modify this file. • R.java File: As you add more files and folders to your project, Eclipse will automatically generate the content of R.java, which at the moment contains the following: • You are not supposed to modify the content of the R.java file; Eclipse automatically generates the content for you when you modify your project.
  • 45. • package net.learn2develop.HelloWorld; • public final class R { • public static final class attr { • } • public static final class drawable { • public static final int icon=0x7f020000; • } • public static final class layout { • public static final int main=0x7f030000; • } • public static final class string { • public static final int app_name=0x7f040001; public static final int hello=0x7f040000; • } }
  • 46. • Snippet 4.2 depicts a sample layout file – activity_main.xml – and the resultant integer constant in the R.java file is listed in Snippet 4.3.
  • 47. Android provides the Layout editor[3] to create the layouts. To create a new layout file, right click on the layout folder of Android app project structure, and then select New → Android XML File, which will pop up the New Android XML File wizard, as depicted in Fig. 4.9. Note: DroidDraw is another popular open source to create layouts.
  • 49. • The Layout editor also provides a mechanism to drag and drop the UI components in the layout file to create the required UI. The equivalent XML layout file gets generated automatically behind the scenes. • Because apps have different requirements for arranging the UI elements (referred to as views in Android context), the Layout editor provides various ready-to-use layouts such as relative, linear, grid, and table. • Relative layout is the default layout of an Activity wherein views (UI elements) are arranged relative to other views in that layout and/or the layout itself. Because views are always placed relative to one another, rendering views happens automatically without any hassles on devices of diverse screen resolutions, sizes, or orientations.
  • 50. • LinearLayout : Arranges views in a single column or single row. • AbsoluteLayout : Enables you to specify the exact location of its children. • TableLayout: Groups views into rows and columns. • RelativeLayout : Enables you to specify how child views are positioned relative to each other. Or RelativeLayout is a view group that displays child views in relative positions. • FrameLayout: A placeholder on screen that you can use to display a single view. • ScrollView: A special type of FrameLayout in that it enables users to scroll through a list of views that occupy more space than the physical display allows. • Unit of Measure : Use dp for specifying the dimension of views and sp for font size.
  • 51. RelativeLayout • To create a relative layout, select RelativeLayout as the root element from New Android XML File wizard, as already explored in Fig. 4.9. This will yield an XML file with RelativeLayout as the root element. • When we use relative layout, there are two types of attributes that can be assigned to views – • To align views relative to one another in the layout or • To align views relative to the layout itself. • For example, as depicted in Fig. 4.10 and Snippet 4.4, • EditText1 is placed relative to its container (RelativeLayout), whereas Button1 and Button2 are placed relative to other views (EditText1 and Button1, respectively).
  • 55. • In Snippet 4.4, EditText1 contains properties such as • layout_alignParentLeft, • layout_alignParentRight, and • layout_alignParentTop • set to true • (Lines 11–13),This ensures that the EditText1 is aligned to the left, right, and top of the parent (RelativeLayout). • Button1 is aligned to the right of its parent (RelativeLayout) using the layout_alignParentRight (Line 21) attribute and • below EditText1 using the layout_below attribute (Line 22). • Button2 is placed to the left of Button1 using the layout_toLeftOf attribute (Line 30).
  • 56. • The layout_alignBaseline and layout_alignBottom attributes (Lines 28 and 29) ensure that the baseline and bottom edge of Button2 are matched with those of Button1 so that both views are in the same line.
  • 57. Linear layout On the other hand, linear layout ensures that UI elements are placed either horizontally or vertically. • It is defined by using the LinearLayout tag in the layout file. • Snippet 4.5 shows how the linear layout canbe used to recreate the screen of LayoutDemo app (shown in Fig. 4.10).
  • 60. • The most important attribute of the linear layout is android:orientation (Line 4). • Using this attribute, we can place the elements horizontally or vertically in the layout. Here, we have set it to vertical. • We can also see that layouts can be nested (see Line 13). The parent LinearLayout now hosts a child • LinearLayout, which in turn contains the two buttons: Button1 and Button2. • Another important attribute of the LinearLayout is android:gravity. • Gravity refers to the alignment of child elements in a container. • In Line 16, the child LinearLayout’s gravity is set as right so that all child elements of this layout would be aligned to the right.
  • 61. String Resources •String resource XML files are kept in resvalues folder. To create a string resource XML file, •Right click on values folder, •Select New → Android XML File, and •Provide the appropriate values in New Android XML File wizard (shown earlier in Fig. 4.9). Editing of this XML file can be done either in a visual XML file editor or a simple text-based editor.
  • 62. • Two most commonly used string resources are string constants and string arrays. • String constant is a simple key–value pair. • You may recall from Snippet 2.4 of Chapter 2 that in the HelloWorld app, string “Helloworld!” is being assigned to the hello_world key in strings.xml resource file, under the <resources> tag. • Similar to a layout resource, a unique id is generated for string constants in the R.java file that may be further used to programmatically access it, as depicted in Snippet 4.6. .
  • 63. 1 Resources resources=getResources(); 2 String message1=resources.getString(R.string.hello); Snippet 4.6 Accessing string constant programmatically • The method getResources() of Resources class is used to access all app resources that are present in the app project structure. • The string resource is further extracted using the getString() method by passing the unique id of string constant (R.string.hello) generated in the R.java file (see Line 2 of Snippet 4.6).
  • 64. • String array is an array of strings assigned to a key. • It is declared in the string resource file using the <string-array> tag, as depicted in Snippet 4.7. • The individual strings in the array are declared using the <item> tag. • The key is declared as name attribute of the <string-array> tag.
  • 65. • The string array resource is extracted from the Resources object using the getStringArray() method by passing the unique id of string array constant (R.array.nations) generated in the R.javafile, as depicted in Line 2 of Snippet 4.8.
  • 66. • String resources are also useful in localizing an app in the case of multilingual rollout. • This is done by placing string resources in locale-specific resource folders such as resvalues-fr and resvalues-hi for French and Hindi, respectively. • All locale equivalents of a specific string resource will use the same key so that Android runtime automatically picks up the appropriate value based on the locale.
  • 67. • Image Resources • The very first place where a user interacts with an image resource is the app icon itself. • There are several other places where images can be incorporated such as in • Image view, • Layout background, • Button, • And some other UI elements to enhance the visual appeal of an app.
  • 68. • Image files are placed in resdrawable folders. • Android provides a mechanism to access these images in app components programmatically or nonprogrammatically. • Programmatically, Resources class is used to access an image resource using the getDrawable() method (see Snippet 4.9). • The return type of this method is Drawable. • The unique id of image resource (R.drawable.filename) has to be passed as parameter to this method. • In this example, ic_launcher is the filename that represents the app icon. 1 Drawable drawable=resources.getDrawable(R.drawable.ic_launcher); Snippet 4.9 Accessing image resource programmatically.
  • 69. • Nonprogrammatically, an image resource is associated with other UI resources or elements in the layout file to set the background of layout or other UI elements, or to display the image itself. • Using @drawable/ filename as the value to the properties that set the background (android:background) of a view, an image resource can be set as the background. • An example of this is shown in Snippet 4.10.
  • 70. • We will take a further deep dive into image resources along with other nitty-gritties of graphics and animations in Chapter 7. • After having an understanding of Activity and UI resources, let us now explore UI elements and associated events to create a functional UI.
  • 71. UI ELEMENTS AND EVENTS • Android provides views to handle data and user interaction for a functional UI. • The user interaction may happen in multiple forms – • Data entry in an editable view, • Display of textual/visual data, or • Triggering of an event based on user actions such as • click of a button, • drag of a list, or • multitouch gestures. • Any user interaction with a view triggers an event associated with it. • Such events need to be handled by a developer to provide required functionalities in views.
  • 72. Event-Handling Paradigm • Each view in Android is an event source. • The event source (view) generates an event object in response to a user action. • This event object is passed on to an event listener, provided this view has registered for that event listener. • Event listener is a specialized interface designed to listen to the generated event, and respond to it through callback methods, also referred to as event handlers.
  • 73. The event-handling paradigm and its related vocabulary are summarized in below Table.
  • 74. UI Elements • UI elements are declared in layout files. • The Layout editor provides a mechanism to drag and drop the required UI components into the layout. • The equivalent XML representing the UI element gets generated automatically in the associated layout file.
  • 75. • Commonly used attributes of a view
  • 76. • layout_width attribute is set to fill_parent, which makes its width occupy the entire width of the screen. • The layout_width attribute is set to wrap_content so that its width will be the width of its content—specifically, the text that is displayed. (for example, Open): • match_parent takes entire screen
  • 77. Button Button, as we have seen earlier, is created using the <Button> tag in a layout file, as also depicted in Snippet • We can access the Button created in a layout resource using the findViewById(int) method. • This method takes the unique id of the Button (Line 2 of Snippet 4.11) as parameter. • The return type of this method is View, and to assign it to a Button reference variable, we have to typecast it to a Button, as
  • 78. • A user can perform various actions on the Button. • One of the most common actions is to click it. • To make a Button respond to the click event, we need to set a listener on it. • The listener associated with handling click events is the OnClickListener. • To set the listener on a Button, we can either let the Activity hosting it implement the OnClickListener interface or pass an anonymous inner class as parameter to the setOnClickListener() method of the Button as shown in Snippet 4.13.
  • 79. The onClick() method is the event handler that is automatically executed when a user clicks the Button.
  • 80. EditText is an Android component used to accept user input. It is created using the <EditText> tag in the layout file as depicted in Snippet 4.14.
  • 81. The findViewById(int) method is used to access the EditText, as shown in Snippet 4.15. As we have seen earlier that the findViewById(int) method returns a View object, therefore we need to typecast this returned object to EditText. 1 EditText editText1=(EditText) findViewById(R.id.editText1); Snippet 4.15 Accessing an EditText.
  • 82. • We use the getText() method to get the text entered by the user, as shown in Snippet 4.16. 1 String enteredText=editText1.getText().toString(); Snippet 4.16 Getting the text entered in EditText. • We may also want to set listeners for various actions on EditText. • One of the common actions is when the user changes the focus away from the view. • The event, listener, and handler associated with this event are specified in Table 4.3, and the respective implementation is shown in Snippet 4.17.
  • 84. Checkbox is an Android component that accepts user input choices. It is created using the <CheckBox> tag in the layout file as depicted in Snippet 4.18. • We can access a CheckBox by using the findViewById(int) method and typecasting the resulting View, as shown in Snippet 4.19.
  • 85. • The most common event on a CheckBox is the CheckedChange event, that is, switching of its state from checked to unchecked or vice versa. • The event, listener, and handler are described in Table 4.4.
  • 87. RadioGroup : is used to define a set of options among which only one can be chosen by the user. • A RadioGroup in turn contains many RadioButtons, which are defined in the layout using the <RadioGroup> and <RadioButton> tags, respectively, as shown in Snippet 4.21.
  • 88. • A RadioGroup defined in the layout file is accessed using the findViewById(int) method. • The View returned from this method is typecasted into RadioGroup so that desired operations can be performed on the obtained view. Snippet 4.22 depicts how a RadioGroup can be accessed. • A change in the state of any RadioButton inside a RadioGroup triggers the CheckedChange event on the RadioGroup. Table 4.5 describes the event handling associated with a RadioGroup.
  • 89. The onCheckedChange() event handler is called with two arguments as depicted in Snippet 4.23. The second argument to this callback method indicates the id of the RadioButton that is checked.
  • 90. ListView: •One of the most common UI elements. •To show a scrollable list of items on the screen wherein each item is selectable. •It is created using the <ListView> tag in the layout file as depicted in Snippet 4.24. The ListView can be populated in two ways: •Either at compile time through a string array resource or •Programmatically at runtime.
  • 91. • Populating ListView at compile time with string array resource is pretty straightforward. • We just need to set android:entries attribute to refer to a string array resource (see Line 5 of Snippet 4.25). The string array resource is depicted in Snippet 4.26.
  • 92. • To populate a ListView at runtime we need to use adapters. • An adapter decouples the data and the ListView in which the data has to be rendered. • To achieve the decoupling, the adapter is first associated with the required data and then it is attached to the ListView. • As data changes, the adapter gets refreshed and eventually refreshes the ListView. • Snippet 4.27 depicts how to populate a ListView at runtime.
  • 93. • In Snippet 4.27, we first access the ListView using the findViewById(int) method (Line 1). • Also, the string array resource used earlier (Snippet 4.26) is now accessed via the getResources(). • getStringArray(int) method and assigned to a variable called nations, which now acts as the data source for the ListView (Line 2). • In Line 3 of Snippet 4.27, we create an adapter as reference to the ListAdapter class. • This adapter is instantiated using an object of ArrayAdapter. • The constructor of ArrayAdapter in this case takes three parameters, viz. context, layout, and array.
  • 94. • The layout parameter specifies how the data obtained from the data source (array) is to be displayed in the ListView. • The array parameter specifies the data source for this adapter. Line 4 of Snippet 4.27 shows how we can attach the adapter onto the ListView. • Once the data is populated in the ListView, the user can perform various actions on it. • Typically, the user clicks on an item in the ListView. • This generates an ItemClick event. • The event handling related to ItemClick of a ListView is shown in Table 4.6.
  • 95. The onItemClick() event handler gets invoked with four arguments: •The ListView in which the item was clicked •The row inside ListView that was clicked •The position of the row that was clicked, and •The id of the row that was clicked. In Line 4 of Snippet 4.28, we have logged the position of the row clicked.
  • 96. • ImageView is a container for image resources. It is created using the <ImageView> tag. • The src attribute resolves the location of the image that needs to be rendered in ImageView, as depicted in Snippet 4.29.
  • 97. An Image can also be rendered in the ImageView programmatically using the setImage- Drawable(Drawable) method, as depicted in Snippet 4.30.
  • 98. Dialog is a modal window displayed on the current Activity that supports the user to perform small tasks related to the Activity in focus. • There are various types of dialogs that are supported in Android such as • AlertDialog, • ProgressDialog, • TimePickerDialog, and • DatePickerDialog. • An AlertDialog is created using a Builder class, as depicted in Snippet 4.31.
  • 100. • The Builder class is an inner class of AlertDialog that is used to set the layout and behavior of the dialog. • We can observe that the Builder allows us to configure the title, message, and buttons of the AlertDialog (Lines 2–15). • An AlertDialog typically shows two buttons, positive and negative, to collect response from the user. • The Builder provides the setPositiveButton() and setNegativeButton() methods to configure this (see Lines 4 and 10). • We have to set listeners to monitor the user’s action on these buttons. In Lines 7 and 13, the user is shown a message on click of any of the buttons using a Toast
  • 101. • Toast is an Android widget used to show unobtrusive messages to the user. • It is created using the Toast class. • To create a Toast message, we have to use the makeText() method that returns a Toast object. • The makeText() method accepts the following parameters – • Context, • Text to be displayed, and • Duration for which the Toast has to be displayed. • Toast is displayed to the user using the show()method.
  • 102. LET’S APPLY: To create the SubscribeActivity for the 3CheersCable app Having learnt how to create an Activity, prepare layouts for it, and add a variety of UI components to it, let us now apply what we have learnt. In this section, • let us create the SubscribeActivity for the 3CheersCable app. • This Activity allows the user to select the channel categories of his or her choice to subscribe to. • The selected channel categories are then displayed on a Confirm subscription dialog window for user confirmation (see Fig. 4.11).
  • 103. Figure 4.11 SubscribeActivity: (a) Subscribe Activity and (b) Confirm subscription dialog window.
  • 104. • For the sake of simplicity, let us break down the process involved in creating this Activity into following simple steps, which are easy to understand and follow: • Step 1: Starting up: • Create a new Android project titled 3CheersCable. • Create a package com.app3c for the subscription module. • Select the latest version of the Android platform available. • Select the Create activity option in the New Android Application wizard and name the Activity as SubscribeActivity.
  • 105. Step 2: Setting up the layout resource • Click Finish. We now have an Android project with a folder structure similar to the HelloWorld app that we had created in Chapter 2. • Then Create a layout resource activity_subscribe.xml in the reslayout folder. • Set the argument passed to the setContentView() method as R.layout. activity_subscribe in the SubscribeActivity.java file in order to allow the Activity to use activity_subscribe.xml as its layout resource.
  • 106. Step 3: Adding UI components: Let us now add UI components to the layout file (activity_subscribe.xml): • Set <RelativeLayout> as the root element in activity_subscribe.xml. • Add TextView to this relative layout by dragging a TextView component from the Form Widgets section of the Palette and dropping it on the Graphical Layout editor. This TextView will work as the title or the heading of this Activity.
  • 107. • The following code is automatically generated in the activity_subscribe.xml file. 1 <TextView 2 android:id=“@+id/textView1” 3 android:layout_width=“wrap_content” 4 android:layout_height=“wrap_content” 5 android:layout_alignParentLeft=“true” 6 android:layout_alignParentTop=“true” 7 android:text=“@string/subs_heading”> 8 </TextView> • The TextView uses a string resource subs_heading whose value has to be set as “Subscribe” in strings.xml.
  • 108. • Similarly, add another TextView to provide instruction – “Select the channel categories you wish to subscribe to”. • Drag and drop a ListView from the Composite section of the Palette. • This will generate the following code in the activity_subscribe.xml file. 1 <ListView 2 android:id=“@+id/listView1” 3 android:layout_width=“match_parent” 4 android:layout_height=“wrap_content” 5 android:layout_marginTop=“80dp” 6 android:layout_alignParentBottom=“true”> 7 </ListView>
  • 109. • The layout_alignParentBottom attribute is set to true so that the ListView does not hide the Button below it. This ListView will display the list of channel categories that the user can subscribe from. • Drag and drop a Button (Next) from the Form Widgets section onto the Graphical Layout editor. 1 <Button 2 android:id=“@+id/button1” 3 android:layout_width=“wrap_content” 4 android:layout_height=“wrap_content” 5 android:layout_alignParentBottom=“true” 6 android:layout_alignRight=“@id/listView1” 7 android:layout_marginRight=“50dp” 8 android:text=“@string/subs_next”/>
  • 110. • Step 4: Setting up the ListView: Let us now populate the ListView created in the previous step: • Create an ArrayAdapter in the onCreate() method that will be used to set the ListAdapter for our ListView. • The ArrayAdapter constructor takes the app context, the layout description of each list item, and the list of objects to display in the ListView, as parameters. 1 ArrayAdapter<String> categoryListAdapter=new ArrayAdapter<String>(this, android.R.layout. simple_list_item_ multiple_choice,category); • The layout description used here is simple_list_item_multiple_choice. • Use this description to add a checkbox to every list item, hence allowing multiple selections.
  • 111. • Create a method getCategoryNames() that will return a list of categories. • This list is used to populate category (the third argument used in the constructor of ArrayAdapter), which will insert these objects in the ListView. 1 public List<String> getCategoryNames(){ 2 List<String> categoryNames=new ArrayList<String>(); 3 categoryNames.add(“Movies”); 4 … 5 return categoryNames; 6 } • These values are hardcoded in this specific exercise, but we shall learn how to fetch these values dynamically through a Web service in Chapter 6.
  • 112. • Insert the following lines of code in the onCreate() method to set the adapter to the ListView and to enable multiple options in the list to be selected. 1 ListView categoryList=(ListView) findViewById(R.id.listView1); 2 categoryList.setAdapter(categoryListAdapter); 3 categoryList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
  • 113. • Step 5: Handling events: Let us handle the Click event on the Button added earlier in the layout. On click of the Button, all the selected channel categories will be displayed in the Confirm subscription dialog window. • Create a reference for the Button in the onCreate() method. 1 Button next= (Button)findViewById(R.id.button1); Register an onClickListener for the Button: 1 next.setOnClickListener(new OnClickListener() { 2 public void onClick(View v) { 3 // TODO Logic for the event handler goes here 4 } 5 });
  • 114. • Get a list of all the selected items from categoryList. • Use a SparseBooleanArray to store the position of the checked items. • Add these items to an ArrayList that will be used to set up the ListView in the dialog. • Add this code to the onClick() callback method. 1 List<String> confirmed=new ArrayList<String>(); 2 SparseBooleanArray sp=categoryList.getCheckedItemPositions(); 3 for(int i=0;i<category.size();i++) { 4 if(sp.get(i)){ 5 confirmed.add(category.get(i));}
  • 115. • Step 6: Creating a dialog: Now let us create the dialog that appears on click of the Next button. • The dialog will have a ListView containing names of the selected channel categories and two buttons to cancel or confirm the selection. • Create a layout file subscribe_dialog in the layout folder. Add a ListView and two Buttons to the layout. • Create a new Dialog object by passing the current Activity as the context and set the content • view of the dialog using the subscribe_dialog layout. This code is written within the onClick() callback method of SubscribeActivity. 1 subscribe_dialog=new Dialog(SubscribeActivity.this); 2 subscribe_dialog.setContentView(R.layout.subscribe_dialog);
  • 116. Populate the ListView in the dialog using the confirmed ArrayList obtained from the previous step: 1 ListView lv=(ListView)subscribe_dialog.findViewById(R.id.listView2); 2 ArrayAdapter<String> la=new ArrayAdapter<String>(SubscribeActivity.this, android.R.layout.simple_list_item_1,confirmed); 3 lv.setAdapter(la); • Notice that we have used subscribe_dialog.findViewById() to obtain the ListView. This is because the ListView here is a part of the dialog, and not of the Activity. • Set the title for the dialog and call the show() method of the dialog. 1 subscribe_dialog.setTitle(“Confirm subscription”); 2 subscribe_dialog.show();
  • 117. INTERACTION AMONG ACTIVITIES So far, we have seen how to create an Activity, define its makeup in a layout file, followed by • Arranging required UI elements in the layout, and • Provide functionality to these elements to respond to user actions. • This discussion was only around a single Activity. • However an app may comprise more than one Activity. For example, an e-mail app typically has an Activity to list all the messages and another one to display a selected message.
  • 118. • In such scenarios, a user has to navigate and share data between Activities. • This leads to the requirement for Activities not only to interact with each other but also to send and receive information between them. • Android provides this mechanism of navigating and sharing information between Activities using Intent. • Intent is a message-passing framework that is used to carry out interaction between Activities and • Also other Android building blocks such as Services and Broadcast Receivers.
  • 119. Let us now explore both the aspects of an Intent with respect to Activities – • Navigation and • Exchange of data between Activities
  • 120. Navigating B:etween Activities: • To navigate to an Activity from another Activity, we make use of an Intent. It is a two-step process, as follows: Step 1: Create an Intent object with two parameters, as depicted in Line 1 of Snippet 4.32. • The first parameter is context and the second parameter is the second (next) Activity to navigate. • Context is an object provided by Android runtime environment to the app. • It contains the global information about the environment in which the app is running. Step 2: Pass this Intent object to startActivity() method, as depicted in Line 2 of Snippet 4.32.
  • 121. • Every Android component needs to get registered in AndroidManifest.xml after implementation. • Therefore, we have to register the Activities created in an app in the manifest file, as shown in Snippet 4.33.
  • 122. Exchanging Data • We can pass data as part of the Intent that can be retrieved by the second (next) Activity. • The simplest way to pass data between Activities is using a key– value pair. We can pass data of types such as boolean, int, float, char, String, arrays, and ArrayList using the key–value pairs. • Line 2 of Snippet 4.34 shows adding of a boolean data to an Intent object, before the next Activity is started. • Data is added as key–value pair using the putExtra() method of the Intent object. • The putExtra() method accepts a String as the first parameter, which is the key and the value corresponding to it as the second parameter. In Snippet 4.34, • key1 signifies the key and true signifies the value key1 holds.
  • 123. The putExtra() method is overloaded and accepts primitive data types, arrays, and ArrayList of these data types. Another way of passing values is by creating an object of type Bundle. It acts like a collection of key–value pairs that can be passed to another Activity. Line 2 of Snippet 4.35 shows creation of a Bundle object. Lines 3–5 show addition of a collection of key–value pairs to the Bundle. This Bundle is added to an Intent object, before the next Activity is started (Line 6).
  • 124. • Now, to retrieve data in the next Activity (at the receiving end), we need to get an instance of the Intent passed from the first Activity. • This is achieved using the getIntent()method. From the Intent object, we have to retrieve the key–value pair either directly (see Snippet 4.36) or from the Bundle object (see Snippet 4.37).
  • 126. • The first parameter is the key that was passed while sending the data. • The second parameter is the default value that must be assigned to the variable in case the key–value pair corresponding to the supplied key is unavailable in the Intent. • In Line 2 of Snippet 4.37, the Bundle that was sent earlier (refer to Snippet 4.35) is retrieved using the getExtras() method. • One of the key–value pairs is retrieved from the Bundle object using the get- Boolean() method, which accepts the key as the first parameter and default value as the second.
  • 128. • In Snippets 4.36 and 4.37, the getIntent() method is used to retrieve the Intent that started • the component. In Line 2 of Snippet 4.36, the boolean data that was sent earlier directly using the • putExtra() method (refer to Snippet 4.34) is retrieved using the getBooleanExtra() method.
  • 129. FRAGMENTS • With the advent of tablets in market, developers got more real estate for an app UI. • Fragments have been introduced to cater to leverage the larger UIs since the advent of Android 3.0 (Honeycomb – API level 11). • Fragments are UI modules and are similar to Activities in many ways. • Fragments allow the flexibility of designing the UI such that in a single screen it is possible to accommodate more than one UI modules. • In such a scenario, typically, Activity acts as a container and hosts multiple Fragments to be shown on a single screen. • shows the corresponding states.
  • 130. • Figure 4.13 depicts two Fragments hosted within an Activity. • Fragment on the left shows a list of nations and that on the right shows the corresponding states.
  • 132. Building Fragments Building Fragments of an app can be broadly categorized into three steps: • Designing the Fragment layout, • Creating Fragment class, and • Associating Fragment to an Activity. Let us now try to understand these steps with an example that will help in achieving the result as depicted in Fig. 4.13.
  • 133. • To start with, we have to design the layout of the Fragment in the associated layout XML file. • As in the example, we have two Fragments: • Nation Fragment and • State Fragment. • We need to define two layout files: • nation_fragment.xml and • state_fragment.xml (see Snippets 4.38 and 4.39, respectively).
  • 136. • The next step is to create a class that extends Fragment (or its subclasses). • This class is required to inflate the Fragment layout and define the behavior of Fragment. Because we have two Fragments, we need to define two Fragment classes: • NationFragment and • StateFragment (see Snippets 4.40 and 4.41,respectively).
  • 139. • In Snippets 4.40 and 4.41, we override the onCreateView() method. • This is one of the life-cycle methods of a Fragment and is used to instantiate the UI of the Fragment. • This method returns a View object, which is the UI of the Fragment, created using the inflate() method of the LayoutInflater class (Lines 5 and 6). • The inflate() method inflates(fill) the Fragment’s UI (defined in the Fragment layout file and passed as the first argument here), and then attaches it to the designated container in the host Activity (passed as the second argument here).
  • 140. • The concluding step is to associate the Fragment(s) to the anchor Activity (MainActivity here). This can be achieved either statically or dynamically. • To associate the Fragment to an Activity in a static manner, we need to add the <fragment> tag in the layout file of the host Activity (see Snippet 4.42). • The <fragment> tag defines the designated container for Fragments, and has most attributes similar to other UI elements in Android. • The most important attribute of the <fragment> tag is android:name that defines the Fragment class to be loaded in the designated container.
  • 141. • As depicted in Lines 10 and 23, the value for android:name attribute is the Fragment class created earlier (NationFragment and StateFragment). • No changes need to be made in the Activity class, and as soon as the Activity is rendered, both Fragments are attached to it and we get the result as shown earlier in Fig. 4.13.
  • 144. • Alternatively, Fragments can be dynamically associated with an Activity using placeholders for them in the layout file of the Activity. Here, this is done using <FrameLayout> tag as shown in Snippet 4.43.
  • 146. • In the onResume() method of the Activity, we attach the required Fragments at runtime using the FragmentManager API (See Snippet 4.44). • In Line 1, an object of FragmentTransaction is obtained from the beginTransaction() method of the FragmentManager class. • FragmentTransaction is used to perform transactions such as • add, • replace, or • remove on Fragments dynamically. • Lines 2 and 3 depict the addition of the Fragments to the Activity using the add() method of the FragmentTransaction class.
  • 147. The add() method accepts the following parameters – • id of the placeholder for the Fragment, • instance of the Fragment, and • a tag with which the Fragment can be referred later, if need be. The commit() method used in Line 4 is the most important line in Snippet 4.44. It commits the transactions performed on the Fragments.
  • 149. • Till now, we have seen how to design a Fragment layout, create a Fragment class, and associate a Fragment to an Activity. Working with Fragments requires us to further understand its life cycle and how they interact with each other. • Let us now explore these two critical aspects in the next two subsections.
  • 150. Life Cycle of Fragments • Similar to an Activity, Fragment too has its own life cycle. Because Fragment is attached to an Activity, the life cycle of a Fragment is intertwined with the Activity. • This results in interlacing of the life-cycle methods of Activity and Fragment. • The Fragment life cycle starts with a call to onAttach() method when a Fragment is added to an Activity. • The next call is to the method onCreate() that is used for initializing instance variables of the Fragment. • onCreateView() method follows onCreate() method to instantiate the UI of the Fragment, as seen earlier in Snippets 4.39 and 4.40.
  • 151. • In this method, we inflate the XML layout file that describes the UI of the Fragment. This is followed by call to the onActivityCreated() method, which is invoked when the host Activity of this Fragment has completed execution of its own onCreate() method. • onStart() is the next method that is invoked when the Fragment becomes visible. • The last method that is called before the Fragment becomes active is onResume(), which enables the user to interact with the Fragment. • When the Fragment transitions from the active to destroyed state, it goes through onPause(), onStop(), onDestroyView(), onDestroy(), and onDetach() callbacks.
  • 152. • The main difference between the life cycle of an Activity and that of a Fragment is that ---- • The Activity life cycle is managed by Android runtime using task stack (refer Section 4.2.1), • Whereas Fragments are managed by the host Activity using back stack mechanism. • The back stack mechanism helps developer to manage multiple Fragment transactions in an Activity.
  • 153. Interaction Between Fragments • Referring to Fig. 4.13, if a user selects another nation, the second Fragment has to be populated with the respective states. • To achieve this, two Fragments have to interact with each other. • In this example, as a single Activity hosts two Fragments, the interaction can be achieved as explained below. • To start with, the NationFragment.java (refer to Snippet 4.40) has to be modified as depicted in Lines 7–12 of Snippet 4.45.
  • 155. • In Line 7 of Snippet 4.45, we access the ListView in the Fragment that displays the list of nations. • In Line 8, we set an OnItemClickListener on the ListView. • The logic inside the onItemClick() handler determines the country clicked by the user and passes that as a parameter to the onFragmentAction() method. • The onFragmentAction() is a user-defined method in the MainActivity class that passes on the selected country to the StateFragment so that the StateFragment can modify the list it is displaying. • The logic of onFragmentAction() method is as shown in Snippet 4.46.
  • 157. • In the onFragmentAction() method, an instance of FragmentManager is obtained as shown in Line 2 of Snippet 4.46. • The obtained instance is further used to access the StateFragment. • The findFragmentByTag() method takes a String variable as parameter and returns the Fragment identified by the tag supplied. • In Line 4, the setList(), a user-defined method of StateFragment is invoked with the country selected by the user as argument. • The definition of setList() method is as shown below in Snippet 4.47.
  • 159. • The setList() method in Snippet 4.47 accepts the country selected by the user. • On the basis of this selection, it populates the required states into states array (see Lines 5 – 11). • The states array is further used in Line 12 to set the adapter of the ListView, thereby ensuring that when a nation is selected in the NationFragment, its corresponding states are displayed in the StateFragment.
  • 160. ACTION BAR • An action bar is a dedicated functional strip on top of the screen that provides exclusive space for displaying varieties of global functionality required in an app such as navigation tabs, search, and user settings. • It is up to the developer to populate action bar with more functionalities that deemed fit to be accessed across the app.
  • 161. • Figure 4.17 shows a typical action bar. Android runtime automatically manages its placement based on the device screen size and orientation. • As shown in the figure, an action bar typically consists of the following elements: 1. App branding (icon and name). 2. Navigation tabs that provide a better way of navigating between the Fragments in a single Activity. 3. Action items such as zoom in and zoom out; Action views such as search in this example that provide a mechanism for the user to perform common functionalities inside an app. 4. Overflow button that holds extra menu options that are not visible by default in an action bar. The extra options surface up when the overflow button is tapped.
  • 163. • Having understood the basic layout of the action bar, let us now implement the action bar. • An action bar is available by default in any app, and it contains the app icon and name. • This is because android:theme attribute in <application> tag is set to Theme.Holo, as shown in Snippet 4.48. • Action bar can be removed by setting the value of android:theme to Theme.NoTitleBar.
  • 165. • Themes are used to maintain consistent look and feel across the app. • Theme.Holo is the default theme in Android Jelly Bean. • We can further populate the action bar with navigation tabs, action views, action items, and overflow button.
  • 169. • Navigation tabs provide a way of switching between multiple Fragments in the same Activity. • Snippet 4.49 depicts how navigation tabs are implemented in an action bar. In Line 7 of Snippet 4.49, we get an instance of ActionBar using the getActionBar() method. • To enable the action bar to display navigation tabs, we use the setNavigationMode() method of the ActionBar as shown in Line 8. • The ActionBar.NAVIGATION_MODE_TABS constant is supplied as a parameter to the setNavigationMode() method to make the action items appear as tabs in the action bar.
  • 170. • In Lines 9–11, we create three tabs using the newTab() method. • Additionally, we also set the text to be displayed on the tab (using the setText() method) and the listener to be triggered when a user selects the tab (using the setTabListener() method). • When we pass this as a parameter to the setTabListener(), it means that the Activity is going to implement the event handler to handle the user action on the tab. • This is another way of achieving event handling in Android unlike what we have already learnt in Section 4.4.2 of this chapter. • In Lines 12–14, we use the addTab() method to add the tabs created in Lines 9–11 to the action bar.
  • 171. • The layout of this Activity contains a FrameLayout with id fragmentContent. This is the container for Fragments in this Activity. • In the onTabSelected() method (Lines 17–35), we obtain the position of the selected tab and replace the Fragment in the container based on the user selection. • Fragment1, Fragment2, and Fragment3 are three Fragments, each containing a TextView. The layouts of these Fragments have been designed, and the classes for these have been created just like how we did earlier in Section 4.8.1 of this chapter. • In Line 34, the replace() method of FragmentTransaction is called to replace an existing Fragment in the container with a new one.
  • 172. • Action views and items provide a mechanism for the user to perform common functionalities inside an app. • To create them in the action bar of an app, we first have to declare a menu resource. • Menu resources are located in the resmenu folder in the project structure of the app. • To create a menu resource XML file, right click on menu folder, select New → Android XML File, and provide the appropriate values in the New Android XML File wizard (shown earlier in Fig. 4.9). • Editing of this XML file can be done using either a visual XML file editor or a simple text-based editor. Snippet 4.50 shows the definition of the menu XML file.
  • 175. Value Description ifRoom Only place this item in the app bar if there is room for it. If there is not room for all the items marked "ifRoom", the items with the lowest orderInCategory values are displayed as actions, and the remaining items are displayed in the overflow menu. withText Also include the title text (defined by android:title) with the action item. You can include this value along with one of the others as a flag set, by separating them with a pipe |.
  • 176. • android:orderInCategory is an integer attribute that dictates the order in which the menu items will appear within the menu when it is displayed. • Menu items in ToolBar are arranged from left to right (or start to end in RTL mode) in the ascending order (i.e. 1,2,3 -> left to right)
  • 177. never Never place this item in the app bar. Instead, list the item in the app bar's overflow menu. always Always place this item in the app bar. Avoid using this unless it's critical that the item always appear in the action bar. Setting multiple items to always appear as action items can result in them overlapping with other UI in the app bar. collapseActi onView The action view associated with this action item is collapsible. (as declared by android:actionLayout or android:actionViewClass) Introduced in API Level 14.
  • 178. • In Snippet 4.50, the menu contains a total of five items. The first item (Lines 3–7) and second item (Lines 8–12) represent the zoom-in and zoom- out buttons (see Fig. 4.17). • These items have android:icon, android:title, and android:showAsAction attributes among other attributes. • The android: icon attribute is used to set an icon to the menu item when it is being displayed. • The value of the android:title attribute is the text that is displayed in the action bar (in this case “Zoom In” and “Zoom Out”). • The value of the android:showAsAction attribute determines when and how the item is shown in the action bar.
  • 179. • The fourth and fifth items (Lines 19–22 and 23–25) do not specify the android:showAsAction attribute. • This results in the appearance of the overflow button on the action bar. • These menu items are displayed only when the user taps on the overflow button in the action bar. • The third item (Lines 13–18) represents a specialized widget in Android called the SearchView. • The SearchView is used to add querying functionality in an app. • The android:actionViewClass attribute defines the look and feel of the widget on the action bar.
  • 180. • Once the menu resource is designed, we need to inflate it in the Activity class using the onCreate-OptionsMenu() method, as shown in Snippet 4.51.
  • 181. Layout Attributes • android:id This is the ID which uniquely identifies the view. • UI element is identified using this unique id. • @+id/id_name is used to set the id. • android:layout_width This is the width of the layout. • android:layout_height This is the height of the layout • android:layout_marginTop This is the extra space on the top side of the layout. • android:layout_marginBottom This is the extra space on the bottom side of the layout. • android:layout_marginLeft This is the extra space on the left side of the layout.
  • 182. • android:layout_gravity This specifies how child Views are positioned. • android:layout_weight This specifies how much of the extra space in the layout should be allocated to the View. • android:layout_x This specifies the x-coordinate of the layout. • android:layout_y This specifies the y-coordinate of the layout. • android:layout_width This is the width of the layout.
  • 183. • android:paddingLeft This is the left padding filled for the layout. • android:paddingRight This is the right padding filled for the layout. • android:paddingTop This is the top padding filled for the layout. • android:paddingBottom This is the bottom padding filled for the layout.
  • 185. • Two ways to adapt to changes in orientation : Anchoring, and resizing and repositioning. • Using different XML files for different orientations: Use the layout folder for portrait UI, and layout-land for landscape UI. • Three ways to persist activity state: Use the onPause() method. Use the onSaveInstanceState() method. Use the onRetainNonConfigurationInstance() method. • Getting the dimension of the current device: Use the WindowManager class’s getDefaultDisplay() method.
  • 186. • Constraining the activity’s orientation: Use the setRequestOrientation() method or the android:screenOrientation attribute in the AndroidManifest.xml file. • Action Bar :Replaces the traditional title bar for older versions of Android. • Action items: Action items are displayed on the right of the Action Bar. They are created just like options menus. • Application icon :Usually used to return to the “home” activity of an application. It is advisable to use the Intent object with the Intent.FLAG_ACTIVITY_CLEAR_TOP flag.
  • 187. View Identification •A view object may have a unique ID assigned to it which will identify the View uniquely within the tree. The syntax for an ID, inside an XML tag is − android:id="@+id/my_button" •Following is a brief description of @ and + signs •The at-symbol (@) at the beginning of the string indicates that the XML parser should parse and expand the rest of the ID string and identify it as an ID resource. •The plus-symbol (+) means that this is a new resource name that must be created and added to our resources. •To create an instance of the view object and capture it from the layout, use the following: