16
Creating an Android Project An Android project contains all the files that comprise the source code for your Android app. The Android SDK tools make it easy to start a new Android project with a set of default project directories and files. This lesson shows how to create a new project either using Eclipse (with the ADT plugin) or using the SDK tools from a command line. Note:  ou should already ha!e the Android SDK installed" and if you#re using Eclipse" you should also ha!e the ADT plugin installed (!ersion $%.&.& or higher). 'f you don#t ha!e these" follow the guide to 'nstalling the Android SDK  efore you start this lesson. Create a Project with Eclipse %. lick New in the toolar . $. 'n th e wind ow tha t appea rs" o pen the Android folder" select Android Application Project " and click Next. Figure 1. The *ew Android App +roject wi,ard in Eclipse. -. ill in th e form that appears/ Application Name is the app name that appears to users. or this project" use 01y irst App.0 Project Name is the name of your project directory and the name !isile in Eclipse. Package Name is the package namespace for your app (following the same rules as  packages in the 2a!a programming language). our package name must e uni3ue across all packages installed on the Android system. or this reason" it#s generally est if you

01 Building Your First App

Embed Size (px)

Citation preview

Page 1: 01 Building Your First App

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 116

Creating an Android Project

An Android project contains all the files that comprise the source code for your Android app The

Android SDK tools make it easy to start a new Android project with a set of default project directories

and filesThis lesson shows how to create a new project either using Eclipse (with the ADT plugin) or using the

SDK tools from a command line

Note ou should already hae the Android SDK installed and if youre using Eclipse you should also

hae the ADT plugin installed (ersion $ampamp or higher) f you dont hae these follow the guide tonstalling the Android SDK efore you start this lesson

Create a Project with Eclipse

lick New in the toolar

$ n the window that appears open the Android folder select Android Application Project andclick Next

Figure 1 The ew Android App +roject wiard in Eclipse- ill in the form that appears

bull Application Name is the app name that appears to users or this project use 01y irst

App0

bull Project Name is the name of your project directory and the name isile in Eclipse

bull Package Name is the package namespace for your app (following the same rules as

packages in the 2aa programming language) our package name must e uni3ue acrossall packages installed on the Android system or this reason its generally est if you

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 216

use a name that egins with the reerse domain name of your organiation or pulisher

entity or this project you can use something like 0come4amplemyfirstapp0 5oweer

you cannot pulish your app on 6oogle +lay using the 0come4ample0 namespace

bull Minimum euired $ is the lowest ersion of Android that your app supports

indicated using the A+ leel To support as many deices as possile you should set

this to the lowest ersion aailale that allows your app to proide its core feature set f

any feature of your app is possile only on newer ersions of Android and its not criticalto the apps core feature set you can enale the feature only when running on the

ersions that support it (as discussed in Supporting Different +latform 7ersions) 8eae

this set to the default alue for this project

bull arget $ indicates the highest ersion of Android (also using the A+ leel) with

which you hae tested with your application

As new ersions of Android ecome aailale you should test your app on the new

ersion and update this alue to match the latest A+ leel in order to take adantage ofnew platform features

bull Compile ampith is the platform ersion against which you will compile your app 9y

default this is set to the latest ersion of Android aailale in your SDK (t should eAndroid or greater if you dont hae such a ersion aailale you must install one

using the SDK 1anager ) ou can still uild your app to support older ersions ut

setting the uild target to the latest ersion allows you to enale new features and

optimie your app for a great user e4perience on the latest deices

bull heme specifies the Android lt style to apply for your app ou can leae this alone

lick Next

=n the ne4t screen to configure the project leae the default selections and click Next

gt The ne4t screen can help you create a launcher icon for your app

ou can customie an icon in seeral ways and the tool generates an icon for all screen

densities 9efore you pulish your app you should e sure your icon meets the specificationsdefined in the conography design guide

lick Next

ow you can select an actiity template from which to egin uilding your app

or this project select lankActi(it) and click Next

8eae all the details for the actiity in their default state and click Finish

our Android project is now set up with some default files and youre ready to egin uilding the appontinue to the ne4t lesson

Create a Project with Command ine oolsf youre not using the Eclipse DE with the ADT plugin you can instead create your project using theSDK tools from a command line

hange directories into the Android SDKs tools path

$ E4ecute

android list targets

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 316

This prints a list of the aailale Android platforms that youe downloaded for your SDK ind

the platform against which you want to compile your app 1ake a note of the target id Be

recommend that you select the highest ersion possile ou can still uild your app to support

older ersions ut setting the uild target to the latest ersion allows you to optimie your appfor the latest deices

f you dont see any targets listed you need to install some using the Android SDK 1anager

tool See Adding +latforms and +ackages

- E4ecute

android create project --target lttarget-idgt --name MyFirstApp --path ltpath-to-workspacegtMyFirstApp --activity MainActivity --package comexamplemyirstapp

Ceplace lttarget-idgt with an id from the list of targets (from the preious step) and replace

ltpath-to-workspacegt with the location in which you want to sae your Android projects

our Android project is now set up with seeral default configurations and youre ready to egin uilding the app ontinue to the ne4t lesson

ip Add the platorm-tools as well as the tools directory to your A enironmentariale

unning +our App

f you followed the preious lesson to create an Android project it includes a default set of 05elloBorld0 source files that allow you to immediately run the app

5ow you run your app depends on two things whether you hae a real Androidpowered deice and

whether youre using Eclipse This lesson shows you how to install and run your app on a real deiceand on the Android emulator and in oth cases with either Eclipse or the command line tools

9efore you run your app you should e aware of a few directories and files in the Android project

AndroidManiestxml

The manifest file descries the fundamental characteristics of the app and defines each of its

components oull learn aout arious declarations in this file as you read more training classes

=ne of the most important elements your manifest should include is the lt$ses-sdkgt element

This declares your apps compatiility with different Android ersions using theandroidminampdkersion and androidtargetampdkersion attriutes or your first

app it should look like this

ltmaniest xmlnsandroid()httpschemasandroidcomapkresandroid) gt lt$ses-sdk androidminampdkersion()) androidtargetampdkersion()+) gt ltmaniestgt

ou should always set the androidtargetampdkersion as high as possile and test your

app on the corresponding platform ersion or more information read Supporting Different

+latform 7ersions

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 416

src

Directory for your apps main source files 9y default it includes an Activity class that runs

when your app is launched using the app iconres

ontains seeral sudirectories for app resources 5ere are just a few

drawale-hdpi

Directory for drawale ojects (such as itmaps) that are designed for highdensity (hdpi)screens =ther drawale directories contain assets designed for other screen densitieslayo$t

Directory for files that define your apps user interface

val$es

Directory for other arious 18 files that contain a collection of resources such as string

and color definitions

Bhen you uild and run the default Android app the default Activity class starts and loads a layout

file that says 05ello Borld0 The result is nothing e4citing ut its important that you understand how

to run your app efore you start deeloping

un on a eal e(ice

f you hae a real Androidpowered deice heres how you can install and run your app

+lug in your deice to your deelopment machine with a ltS9 cale f youre deeloping on

Bindows you might need to install the appropriate ltS9 drier for your deice or helpinstalling driers see the =E1 ltS9 Driers document

$ Enale de-ugging on your deice

bull =n most deices running Android -$ or older you can find the option under ettings

Applications e(elopment

bull =n Android amp and newer its in ettings e(eloper options

Note =n Android $ and newer e(eloper options is hidden y default To make it

aailale go to ettings A-out phone and tap uild num-er seen times Ceturn to

the preious screen to find e(eloper options

To run the app from Eclipse

=pen one of your projects files and click un from the toolar

$ n the un as window that appears select Android Application and click $

Eclipse installs the app on your connected deice and starts it

=r to run your app from a command line

hange directories to the root of your Android project and e4ecuteant de$g

$ 1ake sure the Android SDK platorm-tools directory is included in your A

enironment ariale then e4ecute

ad install inMyFirstApp-de$gapk

- =n your deice locate MyFirstActivity and open it

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 516

Thats how you uild and run your Android app on a deiceF To start deeloping continue to the ne4t

lesson

un on the Emulator

Bhether youre using Eclipse or the command line to run your app on the emulator you need to first

create an Android 7irtual Deice (A7D) An A7D is a deice configuration for the Android emulator

that allows you to model different deices

Figure 1 The A7D 1anager showing a few irtual deices

To create an A7D

8aunch the Android 7irtual Deice 1anager

a n Eclipse click Android 7irtual Deice 1anager from the toolar

rom the command line change directories to ltsdkgttools and e4ecute

android avd

$ n the Android Virtual Device Manager panel click New

- ill in the details for the A7D 6ie it a name a platform target an SD card sie and a skin(576A is default)

lick Create A0

gt Select the new A7D from the Android Virtual Device Manager and click tart After the emulator oots up unlock the emulator screen

To run the app from Eclipse

=pen one of your projects files and click un from the toolar

$ n the un as window that appears select Android Application and click $

Eclipse installs the app on your A7D and starts it

=r to run your app from the command line

hange directories to the root of your Android project and e4ecute

ant de$g

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 616

$ 1ake sure the Android SDK platorm-tools directory is included in your A

enironment ariale then e4ecute

ad install inMyFirstApp-de$gapk

- =n the emulator locate MyFirstActivity and open it

uilding a imple ser nter2ace

The graphical user interface for an Android app is uilt using a hierarchy of iew and iewro$p

ojects iew ojects are usually lt widgets such as uttons or te4t fields and iewro$p ojects

are inisile iew containers that define how the child iews are laid out such as in a grid or a ertical

list

Android proides an 18 ocaulary that corresponds to the suclasses of iew and iewro$p so

you can define your lt in 18 using a hierarchy of lt elements

Alternati(e a)outs

Declaring your lt layout in 18 rather than runtime code is useful for seeral reasons ut its

especially important so you can create different layouts for different screen sies or e4ample you cancreate two ersions of a layout and tell the system to use one on 0small0 screens and the other on

0large0 screens or more information see the class aout Supporting Different Deices

Figure 1 llustration of how iewro$p ojects form ranches in the layout and contain other iew ojects

n this lesson youll create a layout in 18 that includes a te4t field and a utton n the followinglesson youll respond when the utton is pressed y sending the content of the te4t field to another

actiity

Create a inear a)out

=pen the activitymainxml file from the reslayo$t directory

Note n Eclipse when you open a layout file youre first shown the 6raphical 8ayout editor This is

an editor that helps you uild layouts using BSB6 tools or this lesson youre going to work

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 716

directly with the 18 so click the activity_mainxml ta at the ottom of the screen to open the 18

editor

The 9lankActiity template you chose when you created this project includes the

activitymainxml file with a 0elative1ayo$t root iew and a extiew child iew

irst delete the ltextiewgt element and change the lt0elative1ayo$tgt element to

lt1inear1ayo$tgt Then add the androidorientation attriute and set it to

)hori2ontal) The result looks like this

lt3xml version()+4) encoding()$t-)3gtlt1inear1ayo$t xmlnsandroid()httpschemasandroidcomapkresandroid) xmlnstools()httpschemasandroidcomtools) androidlayo$twidth()matchparent) androidlayo$theight()matchparent) androidorientation()hori2ontal) gtlt1inear1ayo$tgt

1inear1ayo$t is a iew group (a suclass of iewro$p) that lays out child iews in either a

ertical or horiontal orientation as specified y the androidorientation attriute Each child

of a 1inear1ayo$t appears on the screen in the order in which it appears in the 18The other two attriutes androidlayo$twidth and androidlayo$theight are

re3uired for all iews in order to specify their sie

9ecause the 1inear1ayo$t is the root iew in the layout it should fill the entire screen area thats

aailale to the app y setting the width and height to )matchparent) This alue declares that the

iew should e4pand its width or height to match the width or height of the parent iew

or more information aout layout properties see the 8ayout guide

Add a ext Field

To create a usereditale te4t field add an lt5ditextgt element inside the lt1inear1ayo$tgt

8ike eery iew oject you must define certain 18 attriutes to specify the 5ditext ojects

properties 5eres how you should declare it inside the lt1inear1ayo$tgt element

lt5ditext androidid()67ideditmessage) androidlayo$twidth()wrapcontent) androidlayo$theight()wrapcontent) androidhint()6stringeditmessage) gt

A-out resource o-jects

A resource oject is simply a uni3ue integer name thats associated with an app resource such as a itmap layout file or string

Eery resource has a corresponding resource oject defined in your projects gen0java file ou

can use the oject names in the 0 class to refer to your resources such as when you need to specify a

string alue for the androidhint attriute ou can also create aritrary resource Ds that you

associate with a iew using the androidid attriute which allows you to reference that iew from

other code

The SDK tools generate the 0java each time you compile your app ou should neer modify this

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 816

file y hand

or more information read the guide to +roiding Cesources

Aout these attriutes

androidid

This proides a uni3ue identifier for the iew which you can use to reference the oject from

your app code such as to read and manipulate the oject (youll see this in the ne4t lesson)

The at sign (6) is re3uired when youre referring to any resource oject from 18 t is followed

y the resource type (id in this case) a slash then the resource name (editmessage)

The plus sign (7) efore the resource type is needed only when youre defining a resource D for

the first time Bhen you compile the app the SDK tools use the D name to create a new

resource D in your projects gen0java file that refers to the 5ditext element =nce the

resource D is declared once this way other references to the D do not need the plus sign ltsing

the plus sign is necessary only when specifying a new resource D and not needed for concreteresources such as strings or layouts See the sideo4 for more information aout resource ojects

androidlayo$twidth and androidlayo$theight

nstead of using specific sies for the width and height the )wrapcontent) alue specifies

that the iew should e only as ig as needed to fit the contents of the iew f you were to

instead use )matchparent) then the 5ditext element would fill the screen ecause it

would match the sie of the parent 1inear1ayo$t or more information see the 8ayouts

guideandroidhint

This is a default string to display when the te4t field is empty nstead of using a hardcoded

string as the alue the )6stringeditmessage) alue refers to a string resource defined

in a separate file 9ecause this refers to a concrete resource (not just an identifier) it does not

need the plus sign 5oweer ecause you haent defined the string resource yet youll see acompiler error at first oull fi4 this in the ne4t section y defining the string

Note This string resource has the same name as the element D editmessage 5oweer

references to resources are always scoped y the resource type (such as id or string) so using

the same name does not cause collisions

Add tring esources

Bhen you need to add te4t in the user interface you should always specify each string as a resource

String resources allow you to manage all lt te4t in a single location which makes it easier to find and

update te4t E4ternaliing the strings also allows you to localie your app to different languages y proiding alternatie definitions for each string resource

9y default your Android project includes a string resource file at resval$esstringsxml

Add a new string named )editmessage) and set the alue to 0Enter a message0 (ou can delete

the 0helloGworld0 string)

Bhile youre in this file also add a 0Send0 string for the utton youll soon add called

)$ttonsend)

The result for stringsxml looks like this

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 916

lt3xml version()+4) encoding()$t-)3gtltreso$rcesgt ltstring name()appname)gtMy First Appltstringgt ltstring name()editmessage)gt5nter a messageltstringgt ltstring name()$ttonsend)gtampendltstringgt ltstring name()actionsettings)gtampettingsltstringgt ltstring name()titleactivitymain)gtMainActivityltstringgtltreso$rcesgt

or more information aout using string resources to localie your app for other languages see the

Supporting Different Deices class

Add a utton

ow add a lt8$ttongt to the layout immediately following the lt5ditextgt element

lt8$tton androidlayo$twidth()wrapcontent) androidlayo$theight()wrapcontent) androidtext()6string$ttonsend) gt

The height and width are set to )wrapcontent) so the utton is only as ig as necessary to fit the

uttons te4t This utton doesnt need the androidid attriute ecause it wont e referenced from

the actiity code

Make the nput ox Fill in the creen ampidth

The layout is currently designed so that oth the 5ditext and 8$tton widgets are only as ig as

necessary to fit their content as shown in figure $

Figure 3 The 5ditext and 8$tton widgets hae their widths set to )wrapcontent)

This works fine for the utton ut not as well for the te4t field ecause the user might type somethinglonger So it would e nice to fill the unused screen width with the te4t field ou can do this inside a

1inear1ayo$t with the weight property which you can specify using the

androidlayo$tweight attriute

The weight alue is a numer that specifies the amount of remaining space each iew should consume

relatie to the amount consumed y siling iews This works kind of like the amount of ingredients in

a drink recipe 0$ parts odka part coffee li3ueur0 means twothirds of the drink is odka ore4ample if you gie one iew a weight of $ and another one a weight of the sum is - so the firstiew fills $H- of the remaining space and the second iew fills the rest f you add a third iew and gie

it a weight of then the first iew (with weight of $) now gets H$ the remaining space while the

remaining two each get H

The default weight for all iews is amp so if you specify any weight alue greater than amp to only oneiew then that iew fills whateer space remains after all iews are gien the space they re3uire So to

fill the remaining space in your layout with the 5ditext element gie it a weight of and leae the

utton with no weight

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1016

lt5ditext androidlayo$tweight()+) gt

n order to improe the layout efficiency when you specify the weight you should change the width of

the 5ditext to e ero (ampdp) Setting the width to ero improes layout performance ecause using

)wrapcontent) as the width re3uires the system to calculate a width that is ultimately irreleant

ecause the weight alue re3uires another width calculation to fill the remaining space

lt5ditext androidlayo$tweight()+) androidlayo$twidth()4dp) gt

igure - shows the result when you assign all weight to the 5ditext element

Figure 4 The 5ditext widget is gien all the layout weight so fills the remaining space in the

1inear1ayo$t

5eres how your complete layout file should now look

lt3xml version()+4) encoding()$t-)3gtlt1inear1ayo$t xmlnsandroid()httpschemasandroidcomapkresandroid) xmlnstools()httpschemasandroidcomtools) androidlayo$twidth()matchparent) androidlayo$theight()matchparent) androidorientation()hori2ontal)gt lt5ditext androidid()67ideditmessage) androidlayo$tweight()+)

androidlayo$twidth()4dp) androidlayo$theight()wrapcontent) androidhint()6stringeditmessage) gt lt8$tton androidlayo$twidth()wrapcontent) androidlayo$theight()wrapcontent) androidtext()6string$ttonsend) gtlt1inear1ayo$tgt

This layout is applied y the default Activity class that the SDK tools generated when you created

the project so you can now run the app to see the results

bull n Eclipse click Cun from the toolar

bull =r from a command line change directories to the root of your Android project and e4ecute

ant de$gad install inMyFirstApp-de$gapk

ontinue to the ne4t lesson to learn how you can respond to utton presses read content from the te4t

field start another actiity and more

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1116

tarting Another Acti(it)

After completing the previous lesson you have an app that shows an activity (a single screen)with a text field and a button In this lesson yoursquoll add some code to MainActivity that starts anew activity when the user clics the end button

Respond to the Send Button

o respond to the buttons on$clic event open the activitymainxml layout file and add theandroidamponlic attribute to the utton elementamp

utton androidamplayoutwidth+wrapcontent androidamplayoutheight+wrapcontent androidamptext+-stringbuttonsend androidamponlic+sendMessage

he androidamponlic attributersquos value sendMessage is the name of a method in youractivity that the system calls when the user clics the button

pen the MainActivity class (located in the pro0ects src directory) and add the correspondingmethodamp

11 alled when the user clics the end button 1public void sendMessage(2iew view) 3 4o something in response to button5

his re6uires that you import the 2iew classamp

import androidview2iew7

Tip In 8clipse press trl 9 hift 9 to import missing classes (md 9 hift 9 on Mac)

In order for the system to match this method to the method name given to androidamponlicthe signature must be exactly as shown pecifically the method mustamp

bull e public

bull ave a void return value

bull ave a 2iew as the only parameter (this will be the 2iew that was cliced)

ext yoursquoll fill in this method to read the contents of the text field and deliver that text toanother activity

Build an Intent

An Intent is an ob0ect that provides runtime binding between separate components (such astwo activities) he Intent represents an apprsquos intent to do something ltou can use intentsfor a wide variety of tass but most often theyrsquore used to start another activity

Inside the sendMessage() method create an Intent to start an activity called4isplayMessageActivityamp

Intent intent + new Intent(this 4isplayMessageActivityclass)7

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1216

he constructor used here taes two parametersamp

bull A ontext as its first parameter (this is used because the Activity class is a subclass ofontext)

bull he lass of the app component to which the system should deliver the Intent (in thiscase the activity that should be started)

Sending an intent to other apps

he intent created in this lesson is whats considered an explicit intent because the Intent specifies the exact app component to which the intent should be given owever intents canalso be implicit in which case the Intent does not specify the desired component but allowsany app installed on the device to respond to the intent as long as it satisfies the meta$dataspecifications for the action thats specified in various Intent parameters =or moreinformation see the class about Interacting with ther Apps

Note he reference to 4isplayMessageActivity will raise an error if yoursquore using an I48 suchas 8clipse because the class doesnrsquot exist yet Ignore the error for now7 yoursquoll create the classsoon

An intent not only allows you to start another activity but it can carry a bundle of data to theactivity as well Inside the sendMessage() method use find2iewyId() to get the 8ditext element and add its text value to the intentamp

Intent intent + new Intent(this 4isplayMessageActivityclass)78ditext editext + (8ditext) find2iewyId(gtideditmessage)7tring message + editextgetext()totring()7intentput8xtra(8gtAM8A8 message)7

Note ltou now need import statements for androidcontentIntent andandroidwidget8ditext ltoull define the 8gtAM8A8 constant in a moment

An Intent can carry a collection of various data types as ey$value pairs called extras heput8xtra() method taes the ey name in the first parameter and the value in the secondparameter

In order for the next activity to 6uery the extra data you should define the ey for your intentsextra using a public constant o add the 8gtAM8A8 definition to the top of theMainActivity classamp

public class MainActivity extends Activity 3 public final static tring 8gtAM8A8 + comexamplemyfirstappM8A87 5

Its generally a good practice to define eys for intent extras using your apps pacage nameas a prefix his ensures they are uni6ue in case your app interacts with other apps

Start the Second Activity

o start an activity call startActivity() and pass it your Intent he system receives this call andstarts an instance of the Activity specified by the Intent

ith this new code the complete sendMessage() method thats invoed by the end button

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1316

now loos lie thisamp

11 alled when the user clics the end button 1public void sendMessage(2iew view) 3 Intent intent + new Intent(this 4isplayMessageActivityclass)7 8ditext editext + (8ditext) find2iewyId(gtideditmessage)7 tring message + editextgetext()totring()7 intentput8xtra(8gtAM8A8 message)7

startActivity(intent)75

ow you need to create the 4isplayMessageActivity class in order for this to wor

Create the Second Activity

Figure 1 he new activity wiBard in 8clipseo create a new activity using 8clipseamp

lic New in the toolbar$ In the window that appears open the Android folder and select Android Activity

lic Net- elect BlanActivity and clic NetC =ill in the activity detailsamp

bull roectamp My=irstApp

bull Activity Na$eamp 4isplayMessageActivity

bull ayout Na$eamp activitydisplaymessage

bull Titleamp My Messagebull ampierarchial arentamp comexamplemyfirstappMainActivity

bull Navigation Typeamp one

lic Finish

If youre using a different I48 or the command line tools create a new file named4isplayMessageActivity0ava in the pro0ects src directory next to the original MainActivity0avafile

pen the 4isplayMessageActivity0ava file If you used 8clipse to create this activityamp

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1416

bull he class already includes an implementation of the re6uired onreate() method

bull heres also an implementation of the onreateptionsMenu() method but you wontneed it for this app so you can remove it

bull heres also an implementation of onptionsItemelected() which handles thebehavior for the action bars Up behavior Deep this one the way it is

ecause the Actionar AEIs are available only on 8ltM (AEI level FF) and higher

you must add a condition around the getActionar() method to chec the current platformversion Additionally you must add the -uppressGint(ewApi) tag to the onreate() method to avoid lint errors

he 4isplayMessageActivity class should now loo lie thisamp

public class 4isplayMessageActivity extends Activity 3 -uppressGint(ewApi) -verride protected void onreate(undle savedInstancetate) 3 superonreate(savedInstancetate)7 setontent2iew(gtlayoutactivitydisplaymessage)7 Mae sure were running on oneycomb or higher to use Actionar AEIs

if (uild28gtI4DI + uild28gtI488ltM) 3 how the Hp button in the action bar getActionar()set4isplayomeAsHp8nabled(true)7 5 5 -verride public boolean onptionsItemelected(MenuItem item) 3 switch (itemgetItemId()) 3 case androidgtidhomeamp avHtilsnavigateHp=romameas(this)7 return true7 5 return superonptionsItemelected(item)7 55

If you used an I48 other than 8clipse update your 4isplayMessageActivity class with theabove code

All subclasses of Activity must implement the onreate() method he system calls this whencreating a new instance of the activity his method is where you must define the activitylayout with the setontent2iew() method and is where you should perform initial setup for theactivity components

Note If you are using an I48 other than 8clipse your pro0ect does not contain theactivitydisplaymessage layout thats re6uested by setontent2iew() hats D because

you will update this method later and wont be using that layout

Add the title string

If you used 8clipse you can sip to the next section because the template provides the titlestring for the new activity

If youre using an I48 other than 8clipse add the new activitys title to the stringsxml fileamp

resources

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1516

string name+titleactivitydisplaymessageMy Messagestringresources

Add it to the $aniest

All activities must be declared in your manifest file AndroidManifestxml using an activity element

hen you use the 8clipse tools to create the activity it creates a default entry If youre usinga different I48 you need to add the manifest entry yourself It should loo lie thisamp

application activity androidampname+comexamplemyfirstapp4isplayMessageActivity androidamplabel+-stringtitleactivitydisplaymessage androidampparentActivityame+comexamplemyfirstappMainActivity meta$data androidampname+androidsupportEAgt8AI2Ilt

androidampvalue+comexamplemyfirstappMainActivity activityapplication

he androidampparentActivityame attribute declares the name of this activitys parent activitywithin the apps logical hierarchy he system uses this value to implement default navigationbehaviors such as Hp navigation on Android CF (AEI level F) and higher ltou can providethe same navigation behaviors for older versions of Android by using the upport Gibrary andadding the meta$data element as shown here

Note ltour Android 4D should already include the latest Android upport Gibrary Itsincluded with the A4 undle but if youre using a different I48 you should have installed it

during the Adding Elatforms and Eacages step hen using the templates in 8clipse theupport Gibrary is automatically added to your app pro0ect (you can see the librarys JAgt filelisted under Android Dependencies) If youre not using 8clipse you need to manually add thelibrary to your pro0ectKfollow the guide for setting up the upport Gibrary then return here

If youre developing with 8clipse you can run the app now but not much happens licingthe end button starts the second activity but it uses a default ello world layout providedby the template ltoull soon update the activity to instead display a custom text view so ifyoure using a different I48 dont worry that the app wont yet compile

Receive the Intent

8very Activity is invoed by an Intent regardless of how the user navigated there ltou can getthe Intent that started your activity by calling getIntent() and retrieve the data contained withinit

In the 4isplayMessageActivity classrsquos onreate() method get the intent and extract themessage delivered by MainActivityamp

Intent intent + getIntent()7tring message + intentgettring8xtra(MainActivity8gtAM8A8)7

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1616

(isplay the )essage

o show the message on the screen create a ext2iew widget and set the text usingsetext() hen add the ext2iew as the root view of the activityrsquos layout by passing it tosetontent2iew()

he complete onreate() method for 4isplayMessageActivity now loos lie thisamp

-verridepublic void onreate(undle savedInstancetate) 3 superonreate(savedInstancetate)7 et the message from the intent Intent intent + getIntent()7 tring message + intentgettring8xtra(MainActivity8gtAM8A8)7 reate the text view ext2iew text2iew + new ext2iew(this)7 text2iewsetextiBe(CL)7 text2iewsetext(message)7 et the text view as the activity layout setontent2iew(text2iew)7

5

ltou can now run the app hen it opens type a message in the text field clic end and themessage appears on the second activity

Figure oth activities in the final app running on Android CL

Page 2: 01 Building Your First App

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 216

use a name that egins with the reerse domain name of your organiation or pulisher

entity or this project you can use something like 0come4amplemyfirstapp0 5oweer

you cannot pulish your app on 6oogle +lay using the 0come4ample0 namespace

bull Minimum euired $ is the lowest ersion of Android that your app supports

indicated using the A+ leel To support as many deices as possile you should set

this to the lowest ersion aailale that allows your app to proide its core feature set f

any feature of your app is possile only on newer ersions of Android and its not criticalto the apps core feature set you can enale the feature only when running on the

ersions that support it (as discussed in Supporting Different +latform 7ersions) 8eae

this set to the default alue for this project

bull arget $ indicates the highest ersion of Android (also using the A+ leel) with

which you hae tested with your application

As new ersions of Android ecome aailale you should test your app on the new

ersion and update this alue to match the latest A+ leel in order to take adantage ofnew platform features

bull Compile ampith is the platform ersion against which you will compile your app 9y

default this is set to the latest ersion of Android aailale in your SDK (t should eAndroid or greater if you dont hae such a ersion aailale you must install one

using the SDK 1anager ) ou can still uild your app to support older ersions ut

setting the uild target to the latest ersion allows you to enale new features and

optimie your app for a great user e4perience on the latest deices

bull heme specifies the Android lt style to apply for your app ou can leae this alone

lick Next

=n the ne4t screen to configure the project leae the default selections and click Next

gt The ne4t screen can help you create a launcher icon for your app

ou can customie an icon in seeral ways and the tool generates an icon for all screen

densities 9efore you pulish your app you should e sure your icon meets the specificationsdefined in the conography design guide

lick Next

ow you can select an actiity template from which to egin uilding your app

or this project select lankActi(it) and click Next

8eae all the details for the actiity in their default state and click Finish

our Android project is now set up with some default files and youre ready to egin uilding the appontinue to the ne4t lesson

Create a Project with Command ine oolsf youre not using the Eclipse DE with the ADT plugin you can instead create your project using theSDK tools from a command line

hange directories into the Android SDKs tools path

$ E4ecute

android list targets

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 316

This prints a list of the aailale Android platforms that youe downloaded for your SDK ind

the platform against which you want to compile your app 1ake a note of the target id Be

recommend that you select the highest ersion possile ou can still uild your app to support

older ersions ut setting the uild target to the latest ersion allows you to optimie your appfor the latest deices

f you dont see any targets listed you need to install some using the Android SDK 1anager

tool See Adding +latforms and +ackages

- E4ecute

android create project --target lttarget-idgt --name MyFirstApp --path ltpath-to-workspacegtMyFirstApp --activity MainActivity --package comexamplemyirstapp

Ceplace lttarget-idgt with an id from the list of targets (from the preious step) and replace

ltpath-to-workspacegt with the location in which you want to sae your Android projects

our Android project is now set up with seeral default configurations and youre ready to egin uilding the app ontinue to the ne4t lesson

ip Add the platorm-tools as well as the tools directory to your A enironmentariale

unning +our App

f you followed the preious lesson to create an Android project it includes a default set of 05elloBorld0 source files that allow you to immediately run the app

5ow you run your app depends on two things whether you hae a real Androidpowered deice and

whether youre using Eclipse This lesson shows you how to install and run your app on a real deiceand on the Android emulator and in oth cases with either Eclipse or the command line tools

9efore you run your app you should e aware of a few directories and files in the Android project

AndroidManiestxml

The manifest file descries the fundamental characteristics of the app and defines each of its

components oull learn aout arious declarations in this file as you read more training classes

=ne of the most important elements your manifest should include is the lt$ses-sdkgt element

This declares your apps compatiility with different Android ersions using theandroidminampdkersion and androidtargetampdkersion attriutes or your first

app it should look like this

ltmaniest xmlnsandroid()httpschemasandroidcomapkresandroid) gt lt$ses-sdk androidminampdkersion()) androidtargetampdkersion()+) gt ltmaniestgt

ou should always set the androidtargetampdkersion as high as possile and test your

app on the corresponding platform ersion or more information read Supporting Different

+latform 7ersions

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 416

src

Directory for your apps main source files 9y default it includes an Activity class that runs

when your app is launched using the app iconres

ontains seeral sudirectories for app resources 5ere are just a few

drawale-hdpi

Directory for drawale ojects (such as itmaps) that are designed for highdensity (hdpi)screens =ther drawale directories contain assets designed for other screen densitieslayo$t

Directory for files that define your apps user interface

val$es

Directory for other arious 18 files that contain a collection of resources such as string

and color definitions

Bhen you uild and run the default Android app the default Activity class starts and loads a layout

file that says 05ello Borld0 The result is nothing e4citing ut its important that you understand how

to run your app efore you start deeloping

un on a eal e(ice

f you hae a real Androidpowered deice heres how you can install and run your app

+lug in your deice to your deelopment machine with a ltS9 cale f youre deeloping on

Bindows you might need to install the appropriate ltS9 drier for your deice or helpinstalling driers see the =E1 ltS9 Driers document

$ Enale de-ugging on your deice

bull =n most deices running Android -$ or older you can find the option under ettings

Applications e(elopment

bull =n Android amp and newer its in ettings e(eloper options

Note =n Android $ and newer e(eloper options is hidden y default To make it

aailale go to ettings A-out phone and tap uild num-er seen times Ceturn to

the preious screen to find e(eloper options

To run the app from Eclipse

=pen one of your projects files and click un from the toolar

$ n the un as window that appears select Android Application and click $

Eclipse installs the app on your connected deice and starts it

=r to run your app from a command line

hange directories to the root of your Android project and e4ecuteant de$g

$ 1ake sure the Android SDK platorm-tools directory is included in your A

enironment ariale then e4ecute

ad install inMyFirstApp-de$gapk

- =n your deice locate MyFirstActivity and open it

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 516

Thats how you uild and run your Android app on a deiceF To start deeloping continue to the ne4t

lesson

un on the Emulator

Bhether youre using Eclipse or the command line to run your app on the emulator you need to first

create an Android 7irtual Deice (A7D) An A7D is a deice configuration for the Android emulator

that allows you to model different deices

Figure 1 The A7D 1anager showing a few irtual deices

To create an A7D

8aunch the Android 7irtual Deice 1anager

a n Eclipse click Android 7irtual Deice 1anager from the toolar

rom the command line change directories to ltsdkgttools and e4ecute

android avd

$ n the Android Virtual Device Manager panel click New

- ill in the details for the A7D 6ie it a name a platform target an SD card sie and a skin(576A is default)

lick Create A0

gt Select the new A7D from the Android Virtual Device Manager and click tart After the emulator oots up unlock the emulator screen

To run the app from Eclipse

=pen one of your projects files and click un from the toolar

$ n the un as window that appears select Android Application and click $

Eclipse installs the app on your A7D and starts it

=r to run your app from the command line

hange directories to the root of your Android project and e4ecute

ant de$g

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 616

$ 1ake sure the Android SDK platorm-tools directory is included in your A

enironment ariale then e4ecute

ad install inMyFirstApp-de$gapk

- =n the emulator locate MyFirstActivity and open it

uilding a imple ser nter2ace

The graphical user interface for an Android app is uilt using a hierarchy of iew and iewro$p

ojects iew ojects are usually lt widgets such as uttons or te4t fields and iewro$p ojects

are inisile iew containers that define how the child iews are laid out such as in a grid or a ertical

list

Android proides an 18 ocaulary that corresponds to the suclasses of iew and iewro$p so

you can define your lt in 18 using a hierarchy of lt elements

Alternati(e a)outs

Declaring your lt layout in 18 rather than runtime code is useful for seeral reasons ut its

especially important so you can create different layouts for different screen sies or e4ample you cancreate two ersions of a layout and tell the system to use one on 0small0 screens and the other on

0large0 screens or more information see the class aout Supporting Different Deices

Figure 1 llustration of how iewro$p ojects form ranches in the layout and contain other iew ojects

n this lesson youll create a layout in 18 that includes a te4t field and a utton n the followinglesson youll respond when the utton is pressed y sending the content of the te4t field to another

actiity

Create a inear a)out

=pen the activitymainxml file from the reslayo$t directory

Note n Eclipse when you open a layout file youre first shown the 6raphical 8ayout editor This is

an editor that helps you uild layouts using BSB6 tools or this lesson youre going to work

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 716

directly with the 18 so click the activity_mainxml ta at the ottom of the screen to open the 18

editor

The 9lankActiity template you chose when you created this project includes the

activitymainxml file with a 0elative1ayo$t root iew and a extiew child iew

irst delete the ltextiewgt element and change the lt0elative1ayo$tgt element to

lt1inear1ayo$tgt Then add the androidorientation attriute and set it to

)hori2ontal) The result looks like this

lt3xml version()+4) encoding()$t-)3gtlt1inear1ayo$t xmlnsandroid()httpschemasandroidcomapkresandroid) xmlnstools()httpschemasandroidcomtools) androidlayo$twidth()matchparent) androidlayo$theight()matchparent) androidorientation()hori2ontal) gtlt1inear1ayo$tgt

1inear1ayo$t is a iew group (a suclass of iewro$p) that lays out child iews in either a

ertical or horiontal orientation as specified y the androidorientation attriute Each child

of a 1inear1ayo$t appears on the screen in the order in which it appears in the 18The other two attriutes androidlayo$twidth and androidlayo$theight are

re3uired for all iews in order to specify their sie

9ecause the 1inear1ayo$t is the root iew in the layout it should fill the entire screen area thats

aailale to the app y setting the width and height to )matchparent) This alue declares that the

iew should e4pand its width or height to match the width or height of the parent iew

or more information aout layout properties see the 8ayout guide

Add a ext Field

To create a usereditale te4t field add an lt5ditextgt element inside the lt1inear1ayo$tgt

8ike eery iew oject you must define certain 18 attriutes to specify the 5ditext ojects

properties 5eres how you should declare it inside the lt1inear1ayo$tgt element

lt5ditext androidid()67ideditmessage) androidlayo$twidth()wrapcontent) androidlayo$theight()wrapcontent) androidhint()6stringeditmessage) gt

A-out resource o-jects

A resource oject is simply a uni3ue integer name thats associated with an app resource such as a itmap layout file or string

Eery resource has a corresponding resource oject defined in your projects gen0java file ou

can use the oject names in the 0 class to refer to your resources such as when you need to specify a

string alue for the androidhint attriute ou can also create aritrary resource Ds that you

associate with a iew using the androidid attriute which allows you to reference that iew from

other code

The SDK tools generate the 0java each time you compile your app ou should neer modify this

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 816

file y hand

or more information read the guide to +roiding Cesources

Aout these attriutes

androidid

This proides a uni3ue identifier for the iew which you can use to reference the oject from

your app code such as to read and manipulate the oject (youll see this in the ne4t lesson)

The at sign (6) is re3uired when youre referring to any resource oject from 18 t is followed

y the resource type (id in this case) a slash then the resource name (editmessage)

The plus sign (7) efore the resource type is needed only when youre defining a resource D for

the first time Bhen you compile the app the SDK tools use the D name to create a new

resource D in your projects gen0java file that refers to the 5ditext element =nce the

resource D is declared once this way other references to the D do not need the plus sign ltsing

the plus sign is necessary only when specifying a new resource D and not needed for concreteresources such as strings or layouts See the sideo4 for more information aout resource ojects

androidlayo$twidth and androidlayo$theight

nstead of using specific sies for the width and height the )wrapcontent) alue specifies

that the iew should e only as ig as needed to fit the contents of the iew f you were to

instead use )matchparent) then the 5ditext element would fill the screen ecause it

would match the sie of the parent 1inear1ayo$t or more information see the 8ayouts

guideandroidhint

This is a default string to display when the te4t field is empty nstead of using a hardcoded

string as the alue the )6stringeditmessage) alue refers to a string resource defined

in a separate file 9ecause this refers to a concrete resource (not just an identifier) it does not

need the plus sign 5oweer ecause you haent defined the string resource yet youll see acompiler error at first oull fi4 this in the ne4t section y defining the string

Note This string resource has the same name as the element D editmessage 5oweer

references to resources are always scoped y the resource type (such as id or string) so using

the same name does not cause collisions

Add tring esources

Bhen you need to add te4t in the user interface you should always specify each string as a resource

String resources allow you to manage all lt te4t in a single location which makes it easier to find and

update te4t E4ternaliing the strings also allows you to localie your app to different languages y proiding alternatie definitions for each string resource

9y default your Android project includes a string resource file at resval$esstringsxml

Add a new string named )editmessage) and set the alue to 0Enter a message0 (ou can delete

the 0helloGworld0 string)

Bhile youre in this file also add a 0Send0 string for the utton youll soon add called

)$ttonsend)

The result for stringsxml looks like this

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 916

lt3xml version()+4) encoding()$t-)3gtltreso$rcesgt ltstring name()appname)gtMy First Appltstringgt ltstring name()editmessage)gt5nter a messageltstringgt ltstring name()$ttonsend)gtampendltstringgt ltstring name()actionsettings)gtampettingsltstringgt ltstring name()titleactivitymain)gtMainActivityltstringgtltreso$rcesgt

or more information aout using string resources to localie your app for other languages see the

Supporting Different Deices class

Add a utton

ow add a lt8$ttongt to the layout immediately following the lt5ditextgt element

lt8$tton androidlayo$twidth()wrapcontent) androidlayo$theight()wrapcontent) androidtext()6string$ttonsend) gt

The height and width are set to )wrapcontent) so the utton is only as ig as necessary to fit the

uttons te4t This utton doesnt need the androidid attriute ecause it wont e referenced from

the actiity code

Make the nput ox Fill in the creen ampidth

The layout is currently designed so that oth the 5ditext and 8$tton widgets are only as ig as

necessary to fit their content as shown in figure $

Figure 3 The 5ditext and 8$tton widgets hae their widths set to )wrapcontent)

This works fine for the utton ut not as well for the te4t field ecause the user might type somethinglonger So it would e nice to fill the unused screen width with the te4t field ou can do this inside a

1inear1ayo$t with the weight property which you can specify using the

androidlayo$tweight attriute

The weight alue is a numer that specifies the amount of remaining space each iew should consume

relatie to the amount consumed y siling iews This works kind of like the amount of ingredients in

a drink recipe 0$ parts odka part coffee li3ueur0 means twothirds of the drink is odka ore4ample if you gie one iew a weight of $ and another one a weight of the sum is - so the firstiew fills $H- of the remaining space and the second iew fills the rest f you add a third iew and gie

it a weight of then the first iew (with weight of $) now gets H$ the remaining space while the

remaining two each get H

The default weight for all iews is amp so if you specify any weight alue greater than amp to only oneiew then that iew fills whateer space remains after all iews are gien the space they re3uire So to

fill the remaining space in your layout with the 5ditext element gie it a weight of and leae the

utton with no weight

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1016

lt5ditext androidlayo$tweight()+) gt

n order to improe the layout efficiency when you specify the weight you should change the width of

the 5ditext to e ero (ampdp) Setting the width to ero improes layout performance ecause using

)wrapcontent) as the width re3uires the system to calculate a width that is ultimately irreleant

ecause the weight alue re3uires another width calculation to fill the remaining space

lt5ditext androidlayo$tweight()+) androidlayo$twidth()4dp) gt

igure - shows the result when you assign all weight to the 5ditext element

Figure 4 The 5ditext widget is gien all the layout weight so fills the remaining space in the

1inear1ayo$t

5eres how your complete layout file should now look

lt3xml version()+4) encoding()$t-)3gtlt1inear1ayo$t xmlnsandroid()httpschemasandroidcomapkresandroid) xmlnstools()httpschemasandroidcomtools) androidlayo$twidth()matchparent) androidlayo$theight()matchparent) androidorientation()hori2ontal)gt lt5ditext androidid()67ideditmessage) androidlayo$tweight()+)

androidlayo$twidth()4dp) androidlayo$theight()wrapcontent) androidhint()6stringeditmessage) gt lt8$tton androidlayo$twidth()wrapcontent) androidlayo$theight()wrapcontent) androidtext()6string$ttonsend) gtlt1inear1ayo$tgt

This layout is applied y the default Activity class that the SDK tools generated when you created

the project so you can now run the app to see the results

bull n Eclipse click Cun from the toolar

bull =r from a command line change directories to the root of your Android project and e4ecute

ant de$gad install inMyFirstApp-de$gapk

ontinue to the ne4t lesson to learn how you can respond to utton presses read content from the te4t

field start another actiity and more

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1116

tarting Another Acti(it)

After completing the previous lesson you have an app that shows an activity (a single screen)with a text field and a button In this lesson yoursquoll add some code to MainActivity that starts anew activity when the user clics the end button

Respond to the Send Button

o respond to the buttons on$clic event open the activitymainxml layout file and add theandroidamponlic attribute to the utton elementamp

utton androidamplayoutwidth+wrapcontent androidamplayoutheight+wrapcontent androidamptext+-stringbuttonsend androidamponlic+sendMessage

he androidamponlic attributersquos value sendMessage is the name of a method in youractivity that the system calls when the user clics the button

pen the MainActivity class (located in the pro0ects src directory) and add the correspondingmethodamp

11 alled when the user clics the end button 1public void sendMessage(2iew view) 3 4o something in response to button5

his re6uires that you import the 2iew classamp

import androidview2iew7

Tip In 8clipse press trl 9 hift 9 to import missing classes (md 9 hift 9 on Mac)

In order for the system to match this method to the method name given to androidamponlicthe signature must be exactly as shown pecifically the method mustamp

bull e public

bull ave a void return value

bull ave a 2iew as the only parameter (this will be the 2iew that was cliced)

ext yoursquoll fill in this method to read the contents of the text field and deliver that text toanother activity

Build an Intent

An Intent is an ob0ect that provides runtime binding between separate components (such astwo activities) he Intent represents an apprsquos intent to do something ltou can use intentsfor a wide variety of tass but most often theyrsquore used to start another activity

Inside the sendMessage() method create an Intent to start an activity called4isplayMessageActivityamp

Intent intent + new Intent(this 4isplayMessageActivityclass)7

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1216

he constructor used here taes two parametersamp

bull A ontext as its first parameter (this is used because the Activity class is a subclass ofontext)

bull he lass of the app component to which the system should deliver the Intent (in thiscase the activity that should be started)

Sending an intent to other apps

he intent created in this lesson is whats considered an explicit intent because the Intent specifies the exact app component to which the intent should be given owever intents canalso be implicit in which case the Intent does not specify the desired component but allowsany app installed on the device to respond to the intent as long as it satisfies the meta$dataspecifications for the action thats specified in various Intent parameters =or moreinformation see the class about Interacting with ther Apps

Note he reference to 4isplayMessageActivity will raise an error if yoursquore using an I48 suchas 8clipse because the class doesnrsquot exist yet Ignore the error for now7 yoursquoll create the classsoon

An intent not only allows you to start another activity but it can carry a bundle of data to theactivity as well Inside the sendMessage() method use find2iewyId() to get the 8ditext element and add its text value to the intentamp

Intent intent + new Intent(this 4isplayMessageActivityclass)78ditext editext + (8ditext) find2iewyId(gtideditmessage)7tring message + editextgetext()totring()7intentput8xtra(8gtAM8A8 message)7

Note ltou now need import statements for androidcontentIntent andandroidwidget8ditext ltoull define the 8gtAM8A8 constant in a moment

An Intent can carry a collection of various data types as ey$value pairs called extras heput8xtra() method taes the ey name in the first parameter and the value in the secondparameter

In order for the next activity to 6uery the extra data you should define the ey for your intentsextra using a public constant o add the 8gtAM8A8 definition to the top of theMainActivity classamp

public class MainActivity extends Activity 3 public final static tring 8gtAM8A8 + comexamplemyfirstappM8A87 5

Its generally a good practice to define eys for intent extras using your apps pacage nameas a prefix his ensures they are uni6ue in case your app interacts with other apps

Start the Second Activity

o start an activity call startActivity() and pass it your Intent he system receives this call andstarts an instance of the Activity specified by the Intent

ith this new code the complete sendMessage() method thats invoed by the end button

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1316

now loos lie thisamp

11 alled when the user clics the end button 1public void sendMessage(2iew view) 3 Intent intent + new Intent(this 4isplayMessageActivityclass)7 8ditext editext + (8ditext) find2iewyId(gtideditmessage)7 tring message + editextgetext()totring()7 intentput8xtra(8gtAM8A8 message)7

startActivity(intent)75

ow you need to create the 4isplayMessageActivity class in order for this to wor

Create the Second Activity

Figure 1 he new activity wiBard in 8clipseo create a new activity using 8clipseamp

lic New in the toolbar$ In the window that appears open the Android folder and select Android Activity

lic Net- elect BlanActivity and clic NetC =ill in the activity detailsamp

bull roectamp My=irstApp

bull Activity Na$eamp 4isplayMessageActivity

bull ayout Na$eamp activitydisplaymessage

bull Titleamp My Messagebull ampierarchial arentamp comexamplemyfirstappMainActivity

bull Navigation Typeamp one

lic Finish

If youre using a different I48 or the command line tools create a new file named4isplayMessageActivity0ava in the pro0ects src directory next to the original MainActivity0avafile

pen the 4isplayMessageActivity0ava file If you used 8clipse to create this activityamp

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1416

bull he class already includes an implementation of the re6uired onreate() method

bull heres also an implementation of the onreateptionsMenu() method but you wontneed it for this app so you can remove it

bull heres also an implementation of onptionsItemelected() which handles thebehavior for the action bars Up behavior Deep this one the way it is

ecause the Actionar AEIs are available only on 8ltM (AEI level FF) and higher

you must add a condition around the getActionar() method to chec the current platformversion Additionally you must add the -uppressGint(ewApi) tag to the onreate() method to avoid lint errors

he 4isplayMessageActivity class should now loo lie thisamp

public class 4isplayMessageActivity extends Activity 3 -uppressGint(ewApi) -verride protected void onreate(undle savedInstancetate) 3 superonreate(savedInstancetate)7 setontent2iew(gtlayoutactivitydisplaymessage)7 Mae sure were running on oneycomb or higher to use Actionar AEIs

if (uild28gtI4DI + uild28gtI488ltM) 3 how the Hp button in the action bar getActionar()set4isplayomeAsHp8nabled(true)7 5 5 -verride public boolean onptionsItemelected(MenuItem item) 3 switch (itemgetItemId()) 3 case androidgtidhomeamp avHtilsnavigateHp=romameas(this)7 return true7 5 return superonptionsItemelected(item)7 55

If you used an I48 other than 8clipse update your 4isplayMessageActivity class with theabove code

All subclasses of Activity must implement the onreate() method he system calls this whencreating a new instance of the activity his method is where you must define the activitylayout with the setontent2iew() method and is where you should perform initial setup for theactivity components

Note If you are using an I48 other than 8clipse your pro0ect does not contain theactivitydisplaymessage layout thats re6uested by setontent2iew() hats D because

you will update this method later and wont be using that layout

Add the title string

If you used 8clipse you can sip to the next section because the template provides the titlestring for the new activity

If youre using an I48 other than 8clipse add the new activitys title to the stringsxml fileamp

resources

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1516

string name+titleactivitydisplaymessageMy Messagestringresources

Add it to the $aniest

All activities must be declared in your manifest file AndroidManifestxml using an activity element

hen you use the 8clipse tools to create the activity it creates a default entry If youre usinga different I48 you need to add the manifest entry yourself It should loo lie thisamp

application activity androidampname+comexamplemyfirstapp4isplayMessageActivity androidamplabel+-stringtitleactivitydisplaymessage androidampparentActivityame+comexamplemyfirstappMainActivity meta$data androidampname+androidsupportEAgt8AI2Ilt

androidampvalue+comexamplemyfirstappMainActivity activityapplication

he androidampparentActivityame attribute declares the name of this activitys parent activitywithin the apps logical hierarchy he system uses this value to implement default navigationbehaviors such as Hp navigation on Android CF (AEI level F) and higher ltou can providethe same navigation behaviors for older versions of Android by using the upport Gibrary andadding the meta$data element as shown here

Note ltour Android 4D should already include the latest Android upport Gibrary Itsincluded with the A4 undle but if youre using a different I48 you should have installed it

during the Adding Elatforms and Eacages step hen using the templates in 8clipse theupport Gibrary is automatically added to your app pro0ect (you can see the librarys JAgt filelisted under Android Dependencies) If youre not using 8clipse you need to manually add thelibrary to your pro0ectKfollow the guide for setting up the upport Gibrary then return here

If youre developing with 8clipse you can run the app now but not much happens licingthe end button starts the second activity but it uses a default ello world layout providedby the template ltoull soon update the activity to instead display a custom text view so ifyoure using a different I48 dont worry that the app wont yet compile

Receive the Intent

8very Activity is invoed by an Intent regardless of how the user navigated there ltou can getthe Intent that started your activity by calling getIntent() and retrieve the data contained withinit

In the 4isplayMessageActivity classrsquos onreate() method get the intent and extract themessage delivered by MainActivityamp

Intent intent + getIntent()7tring message + intentgettring8xtra(MainActivity8gtAM8A8)7

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1616

(isplay the )essage

o show the message on the screen create a ext2iew widget and set the text usingsetext() hen add the ext2iew as the root view of the activityrsquos layout by passing it tosetontent2iew()

he complete onreate() method for 4isplayMessageActivity now loos lie thisamp

-verridepublic void onreate(undle savedInstancetate) 3 superonreate(savedInstancetate)7 et the message from the intent Intent intent + getIntent()7 tring message + intentgettring8xtra(MainActivity8gtAM8A8)7 reate the text view ext2iew text2iew + new ext2iew(this)7 text2iewsetextiBe(CL)7 text2iewsetext(message)7 et the text view as the activity layout setontent2iew(text2iew)7

5

ltou can now run the app hen it opens type a message in the text field clic end and themessage appears on the second activity

Figure oth activities in the final app running on Android CL

Page 3: 01 Building Your First App

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 316

This prints a list of the aailale Android platforms that youe downloaded for your SDK ind

the platform against which you want to compile your app 1ake a note of the target id Be

recommend that you select the highest ersion possile ou can still uild your app to support

older ersions ut setting the uild target to the latest ersion allows you to optimie your appfor the latest deices

f you dont see any targets listed you need to install some using the Android SDK 1anager

tool See Adding +latforms and +ackages

- E4ecute

android create project --target lttarget-idgt --name MyFirstApp --path ltpath-to-workspacegtMyFirstApp --activity MainActivity --package comexamplemyirstapp

Ceplace lttarget-idgt with an id from the list of targets (from the preious step) and replace

ltpath-to-workspacegt with the location in which you want to sae your Android projects

our Android project is now set up with seeral default configurations and youre ready to egin uilding the app ontinue to the ne4t lesson

ip Add the platorm-tools as well as the tools directory to your A enironmentariale

unning +our App

f you followed the preious lesson to create an Android project it includes a default set of 05elloBorld0 source files that allow you to immediately run the app

5ow you run your app depends on two things whether you hae a real Androidpowered deice and

whether youre using Eclipse This lesson shows you how to install and run your app on a real deiceand on the Android emulator and in oth cases with either Eclipse or the command line tools

9efore you run your app you should e aware of a few directories and files in the Android project

AndroidManiestxml

The manifest file descries the fundamental characteristics of the app and defines each of its

components oull learn aout arious declarations in this file as you read more training classes

=ne of the most important elements your manifest should include is the lt$ses-sdkgt element

This declares your apps compatiility with different Android ersions using theandroidminampdkersion and androidtargetampdkersion attriutes or your first

app it should look like this

ltmaniest xmlnsandroid()httpschemasandroidcomapkresandroid) gt lt$ses-sdk androidminampdkersion()) androidtargetampdkersion()+) gt ltmaniestgt

ou should always set the androidtargetampdkersion as high as possile and test your

app on the corresponding platform ersion or more information read Supporting Different

+latform 7ersions

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 416

src

Directory for your apps main source files 9y default it includes an Activity class that runs

when your app is launched using the app iconres

ontains seeral sudirectories for app resources 5ere are just a few

drawale-hdpi

Directory for drawale ojects (such as itmaps) that are designed for highdensity (hdpi)screens =ther drawale directories contain assets designed for other screen densitieslayo$t

Directory for files that define your apps user interface

val$es

Directory for other arious 18 files that contain a collection of resources such as string

and color definitions

Bhen you uild and run the default Android app the default Activity class starts and loads a layout

file that says 05ello Borld0 The result is nothing e4citing ut its important that you understand how

to run your app efore you start deeloping

un on a eal e(ice

f you hae a real Androidpowered deice heres how you can install and run your app

+lug in your deice to your deelopment machine with a ltS9 cale f youre deeloping on

Bindows you might need to install the appropriate ltS9 drier for your deice or helpinstalling driers see the =E1 ltS9 Driers document

$ Enale de-ugging on your deice

bull =n most deices running Android -$ or older you can find the option under ettings

Applications e(elopment

bull =n Android amp and newer its in ettings e(eloper options

Note =n Android $ and newer e(eloper options is hidden y default To make it

aailale go to ettings A-out phone and tap uild num-er seen times Ceturn to

the preious screen to find e(eloper options

To run the app from Eclipse

=pen one of your projects files and click un from the toolar

$ n the un as window that appears select Android Application and click $

Eclipse installs the app on your connected deice and starts it

=r to run your app from a command line

hange directories to the root of your Android project and e4ecuteant de$g

$ 1ake sure the Android SDK platorm-tools directory is included in your A

enironment ariale then e4ecute

ad install inMyFirstApp-de$gapk

- =n your deice locate MyFirstActivity and open it

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 516

Thats how you uild and run your Android app on a deiceF To start deeloping continue to the ne4t

lesson

un on the Emulator

Bhether youre using Eclipse or the command line to run your app on the emulator you need to first

create an Android 7irtual Deice (A7D) An A7D is a deice configuration for the Android emulator

that allows you to model different deices

Figure 1 The A7D 1anager showing a few irtual deices

To create an A7D

8aunch the Android 7irtual Deice 1anager

a n Eclipse click Android 7irtual Deice 1anager from the toolar

rom the command line change directories to ltsdkgttools and e4ecute

android avd

$ n the Android Virtual Device Manager panel click New

- ill in the details for the A7D 6ie it a name a platform target an SD card sie and a skin(576A is default)

lick Create A0

gt Select the new A7D from the Android Virtual Device Manager and click tart After the emulator oots up unlock the emulator screen

To run the app from Eclipse

=pen one of your projects files and click un from the toolar

$ n the un as window that appears select Android Application and click $

Eclipse installs the app on your A7D and starts it

=r to run your app from the command line

hange directories to the root of your Android project and e4ecute

ant de$g

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 616

$ 1ake sure the Android SDK platorm-tools directory is included in your A

enironment ariale then e4ecute

ad install inMyFirstApp-de$gapk

- =n the emulator locate MyFirstActivity and open it

uilding a imple ser nter2ace

The graphical user interface for an Android app is uilt using a hierarchy of iew and iewro$p

ojects iew ojects are usually lt widgets such as uttons or te4t fields and iewro$p ojects

are inisile iew containers that define how the child iews are laid out such as in a grid or a ertical

list

Android proides an 18 ocaulary that corresponds to the suclasses of iew and iewro$p so

you can define your lt in 18 using a hierarchy of lt elements

Alternati(e a)outs

Declaring your lt layout in 18 rather than runtime code is useful for seeral reasons ut its

especially important so you can create different layouts for different screen sies or e4ample you cancreate two ersions of a layout and tell the system to use one on 0small0 screens and the other on

0large0 screens or more information see the class aout Supporting Different Deices

Figure 1 llustration of how iewro$p ojects form ranches in the layout and contain other iew ojects

n this lesson youll create a layout in 18 that includes a te4t field and a utton n the followinglesson youll respond when the utton is pressed y sending the content of the te4t field to another

actiity

Create a inear a)out

=pen the activitymainxml file from the reslayo$t directory

Note n Eclipse when you open a layout file youre first shown the 6raphical 8ayout editor This is

an editor that helps you uild layouts using BSB6 tools or this lesson youre going to work

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 716

directly with the 18 so click the activity_mainxml ta at the ottom of the screen to open the 18

editor

The 9lankActiity template you chose when you created this project includes the

activitymainxml file with a 0elative1ayo$t root iew and a extiew child iew

irst delete the ltextiewgt element and change the lt0elative1ayo$tgt element to

lt1inear1ayo$tgt Then add the androidorientation attriute and set it to

)hori2ontal) The result looks like this

lt3xml version()+4) encoding()$t-)3gtlt1inear1ayo$t xmlnsandroid()httpschemasandroidcomapkresandroid) xmlnstools()httpschemasandroidcomtools) androidlayo$twidth()matchparent) androidlayo$theight()matchparent) androidorientation()hori2ontal) gtlt1inear1ayo$tgt

1inear1ayo$t is a iew group (a suclass of iewro$p) that lays out child iews in either a

ertical or horiontal orientation as specified y the androidorientation attriute Each child

of a 1inear1ayo$t appears on the screen in the order in which it appears in the 18The other two attriutes androidlayo$twidth and androidlayo$theight are

re3uired for all iews in order to specify their sie

9ecause the 1inear1ayo$t is the root iew in the layout it should fill the entire screen area thats

aailale to the app y setting the width and height to )matchparent) This alue declares that the

iew should e4pand its width or height to match the width or height of the parent iew

or more information aout layout properties see the 8ayout guide

Add a ext Field

To create a usereditale te4t field add an lt5ditextgt element inside the lt1inear1ayo$tgt

8ike eery iew oject you must define certain 18 attriutes to specify the 5ditext ojects

properties 5eres how you should declare it inside the lt1inear1ayo$tgt element

lt5ditext androidid()67ideditmessage) androidlayo$twidth()wrapcontent) androidlayo$theight()wrapcontent) androidhint()6stringeditmessage) gt

A-out resource o-jects

A resource oject is simply a uni3ue integer name thats associated with an app resource such as a itmap layout file or string

Eery resource has a corresponding resource oject defined in your projects gen0java file ou

can use the oject names in the 0 class to refer to your resources such as when you need to specify a

string alue for the androidhint attriute ou can also create aritrary resource Ds that you

associate with a iew using the androidid attriute which allows you to reference that iew from

other code

The SDK tools generate the 0java each time you compile your app ou should neer modify this

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 816

file y hand

or more information read the guide to +roiding Cesources

Aout these attriutes

androidid

This proides a uni3ue identifier for the iew which you can use to reference the oject from

your app code such as to read and manipulate the oject (youll see this in the ne4t lesson)

The at sign (6) is re3uired when youre referring to any resource oject from 18 t is followed

y the resource type (id in this case) a slash then the resource name (editmessage)

The plus sign (7) efore the resource type is needed only when youre defining a resource D for

the first time Bhen you compile the app the SDK tools use the D name to create a new

resource D in your projects gen0java file that refers to the 5ditext element =nce the

resource D is declared once this way other references to the D do not need the plus sign ltsing

the plus sign is necessary only when specifying a new resource D and not needed for concreteresources such as strings or layouts See the sideo4 for more information aout resource ojects

androidlayo$twidth and androidlayo$theight

nstead of using specific sies for the width and height the )wrapcontent) alue specifies

that the iew should e only as ig as needed to fit the contents of the iew f you were to

instead use )matchparent) then the 5ditext element would fill the screen ecause it

would match the sie of the parent 1inear1ayo$t or more information see the 8ayouts

guideandroidhint

This is a default string to display when the te4t field is empty nstead of using a hardcoded

string as the alue the )6stringeditmessage) alue refers to a string resource defined

in a separate file 9ecause this refers to a concrete resource (not just an identifier) it does not

need the plus sign 5oweer ecause you haent defined the string resource yet youll see acompiler error at first oull fi4 this in the ne4t section y defining the string

Note This string resource has the same name as the element D editmessage 5oweer

references to resources are always scoped y the resource type (such as id or string) so using

the same name does not cause collisions

Add tring esources

Bhen you need to add te4t in the user interface you should always specify each string as a resource

String resources allow you to manage all lt te4t in a single location which makes it easier to find and

update te4t E4ternaliing the strings also allows you to localie your app to different languages y proiding alternatie definitions for each string resource

9y default your Android project includes a string resource file at resval$esstringsxml

Add a new string named )editmessage) and set the alue to 0Enter a message0 (ou can delete

the 0helloGworld0 string)

Bhile youre in this file also add a 0Send0 string for the utton youll soon add called

)$ttonsend)

The result for stringsxml looks like this

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 916

lt3xml version()+4) encoding()$t-)3gtltreso$rcesgt ltstring name()appname)gtMy First Appltstringgt ltstring name()editmessage)gt5nter a messageltstringgt ltstring name()$ttonsend)gtampendltstringgt ltstring name()actionsettings)gtampettingsltstringgt ltstring name()titleactivitymain)gtMainActivityltstringgtltreso$rcesgt

or more information aout using string resources to localie your app for other languages see the

Supporting Different Deices class

Add a utton

ow add a lt8$ttongt to the layout immediately following the lt5ditextgt element

lt8$tton androidlayo$twidth()wrapcontent) androidlayo$theight()wrapcontent) androidtext()6string$ttonsend) gt

The height and width are set to )wrapcontent) so the utton is only as ig as necessary to fit the

uttons te4t This utton doesnt need the androidid attriute ecause it wont e referenced from

the actiity code

Make the nput ox Fill in the creen ampidth

The layout is currently designed so that oth the 5ditext and 8$tton widgets are only as ig as

necessary to fit their content as shown in figure $

Figure 3 The 5ditext and 8$tton widgets hae their widths set to )wrapcontent)

This works fine for the utton ut not as well for the te4t field ecause the user might type somethinglonger So it would e nice to fill the unused screen width with the te4t field ou can do this inside a

1inear1ayo$t with the weight property which you can specify using the

androidlayo$tweight attriute

The weight alue is a numer that specifies the amount of remaining space each iew should consume

relatie to the amount consumed y siling iews This works kind of like the amount of ingredients in

a drink recipe 0$ parts odka part coffee li3ueur0 means twothirds of the drink is odka ore4ample if you gie one iew a weight of $ and another one a weight of the sum is - so the firstiew fills $H- of the remaining space and the second iew fills the rest f you add a third iew and gie

it a weight of then the first iew (with weight of $) now gets H$ the remaining space while the

remaining two each get H

The default weight for all iews is amp so if you specify any weight alue greater than amp to only oneiew then that iew fills whateer space remains after all iews are gien the space they re3uire So to

fill the remaining space in your layout with the 5ditext element gie it a weight of and leae the

utton with no weight

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1016

lt5ditext androidlayo$tweight()+) gt

n order to improe the layout efficiency when you specify the weight you should change the width of

the 5ditext to e ero (ampdp) Setting the width to ero improes layout performance ecause using

)wrapcontent) as the width re3uires the system to calculate a width that is ultimately irreleant

ecause the weight alue re3uires another width calculation to fill the remaining space

lt5ditext androidlayo$tweight()+) androidlayo$twidth()4dp) gt

igure - shows the result when you assign all weight to the 5ditext element

Figure 4 The 5ditext widget is gien all the layout weight so fills the remaining space in the

1inear1ayo$t

5eres how your complete layout file should now look

lt3xml version()+4) encoding()$t-)3gtlt1inear1ayo$t xmlnsandroid()httpschemasandroidcomapkresandroid) xmlnstools()httpschemasandroidcomtools) androidlayo$twidth()matchparent) androidlayo$theight()matchparent) androidorientation()hori2ontal)gt lt5ditext androidid()67ideditmessage) androidlayo$tweight()+)

androidlayo$twidth()4dp) androidlayo$theight()wrapcontent) androidhint()6stringeditmessage) gt lt8$tton androidlayo$twidth()wrapcontent) androidlayo$theight()wrapcontent) androidtext()6string$ttonsend) gtlt1inear1ayo$tgt

This layout is applied y the default Activity class that the SDK tools generated when you created

the project so you can now run the app to see the results

bull n Eclipse click Cun from the toolar

bull =r from a command line change directories to the root of your Android project and e4ecute

ant de$gad install inMyFirstApp-de$gapk

ontinue to the ne4t lesson to learn how you can respond to utton presses read content from the te4t

field start another actiity and more

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1116

tarting Another Acti(it)

After completing the previous lesson you have an app that shows an activity (a single screen)with a text field and a button In this lesson yoursquoll add some code to MainActivity that starts anew activity when the user clics the end button

Respond to the Send Button

o respond to the buttons on$clic event open the activitymainxml layout file and add theandroidamponlic attribute to the utton elementamp

utton androidamplayoutwidth+wrapcontent androidamplayoutheight+wrapcontent androidamptext+-stringbuttonsend androidamponlic+sendMessage

he androidamponlic attributersquos value sendMessage is the name of a method in youractivity that the system calls when the user clics the button

pen the MainActivity class (located in the pro0ects src directory) and add the correspondingmethodamp

11 alled when the user clics the end button 1public void sendMessage(2iew view) 3 4o something in response to button5

his re6uires that you import the 2iew classamp

import androidview2iew7

Tip In 8clipse press trl 9 hift 9 to import missing classes (md 9 hift 9 on Mac)

In order for the system to match this method to the method name given to androidamponlicthe signature must be exactly as shown pecifically the method mustamp

bull e public

bull ave a void return value

bull ave a 2iew as the only parameter (this will be the 2iew that was cliced)

ext yoursquoll fill in this method to read the contents of the text field and deliver that text toanother activity

Build an Intent

An Intent is an ob0ect that provides runtime binding between separate components (such astwo activities) he Intent represents an apprsquos intent to do something ltou can use intentsfor a wide variety of tass but most often theyrsquore used to start another activity

Inside the sendMessage() method create an Intent to start an activity called4isplayMessageActivityamp

Intent intent + new Intent(this 4isplayMessageActivityclass)7

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1216

he constructor used here taes two parametersamp

bull A ontext as its first parameter (this is used because the Activity class is a subclass ofontext)

bull he lass of the app component to which the system should deliver the Intent (in thiscase the activity that should be started)

Sending an intent to other apps

he intent created in this lesson is whats considered an explicit intent because the Intent specifies the exact app component to which the intent should be given owever intents canalso be implicit in which case the Intent does not specify the desired component but allowsany app installed on the device to respond to the intent as long as it satisfies the meta$dataspecifications for the action thats specified in various Intent parameters =or moreinformation see the class about Interacting with ther Apps

Note he reference to 4isplayMessageActivity will raise an error if yoursquore using an I48 suchas 8clipse because the class doesnrsquot exist yet Ignore the error for now7 yoursquoll create the classsoon

An intent not only allows you to start another activity but it can carry a bundle of data to theactivity as well Inside the sendMessage() method use find2iewyId() to get the 8ditext element and add its text value to the intentamp

Intent intent + new Intent(this 4isplayMessageActivityclass)78ditext editext + (8ditext) find2iewyId(gtideditmessage)7tring message + editextgetext()totring()7intentput8xtra(8gtAM8A8 message)7

Note ltou now need import statements for androidcontentIntent andandroidwidget8ditext ltoull define the 8gtAM8A8 constant in a moment

An Intent can carry a collection of various data types as ey$value pairs called extras heput8xtra() method taes the ey name in the first parameter and the value in the secondparameter

In order for the next activity to 6uery the extra data you should define the ey for your intentsextra using a public constant o add the 8gtAM8A8 definition to the top of theMainActivity classamp

public class MainActivity extends Activity 3 public final static tring 8gtAM8A8 + comexamplemyfirstappM8A87 5

Its generally a good practice to define eys for intent extras using your apps pacage nameas a prefix his ensures they are uni6ue in case your app interacts with other apps

Start the Second Activity

o start an activity call startActivity() and pass it your Intent he system receives this call andstarts an instance of the Activity specified by the Intent

ith this new code the complete sendMessage() method thats invoed by the end button

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1316

now loos lie thisamp

11 alled when the user clics the end button 1public void sendMessage(2iew view) 3 Intent intent + new Intent(this 4isplayMessageActivityclass)7 8ditext editext + (8ditext) find2iewyId(gtideditmessage)7 tring message + editextgetext()totring()7 intentput8xtra(8gtAM8A8 message)7

startActivity(intent)75

ow you need to create the 4isplayMessageActivity class in order for this to wor

Create the Second Activity

Figure 1 he new activity wiBard in 8clipseo create a new activity using 8clipseamp

lic New in the toolbar$ In the window that appears open the Android folder and select Android Activity

lic Net- elect BlanActivity and clic NetC =ill in the activity detailsamp

bull roectamp My=irstApp

bull Activity Na$eamp 4isplayMessageActivity

bull ayout Na$eamp activitydisplaymessage

bull Titleamp My Messagebull ampierarchial arentamp comexamplemyfirstappMainActivity

bull Navigation Typeamp one

lic Finish

If youre using a different I48 or the command line tools create a new file named4isplayMessageActivity0ava in the pro0ects src directory next to the original MainActivity0avafile

pen the 4isplayMessageActivity0ava file If you used 8clipse to create this activityamp

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1416

bull he class already includes an implementation of the re6uired onreate() method

bull heres also an implementation of the onreateptionsMenu() method but you wontneed it for this app so you can remove it

bull heres also an implementation of onptionsItemelected() which handles thebehavior for the action bars Up behavior Deep this one the way it is

ecause the Actionar AEIs are available only on 8ltM (AEI level FF) and higher

you must add a condition around the getActionar() method to chec the current platformversion Additionally you must add the -uppressGint(ewApi) tag to the onreate() method to avoid lint errors

he 4isplayMessageActivity class should now loo lie thisamp

public class 4isplayMessageActivity extends Activity 3 -uppressGint(ewApi) -verride protected void onreate(undle savedInstancetate) 3 superonreate(savedInstancetate)7 setontent2iew(gtlayoutactivitydisplaymessage)7 Mae sure were running on oneycomb or higher to use Actionar AEIs

if (uild28gtI4DI + uild28gtI488ltM) 3 how the Hp button in the action bar getActionar()set4isplayomeAsHp8nabled(true)7 5 5 -verride public boolean onptionsItemelected(MenuItem item) 3 switch (itemgetItemId()) 3 case androidgtidhomeamp avHtilsnavigateHp=romameas(this)7 return true7 5 return superonptionsItemelected(item)7 55

If you used an I48 other than 8clipse update your 4isplayMessageActivity class with theabove code

All subclasses of Activity must implement the onreate() method he system calls this whencreating a new instance of the activity his method is where you must define the activitylayout with the setontent2iew() method and is where you should perform initial setup for theactivity components

Note If you are using an I48 other than 8clipse your pro0ect does not contain theactivitydisplaymessage layout thats re6uested by setontent2iew() hats D because

you will update this method later and wont be using that layout

Add the title string

If you used 8clipse you can sip to the next section because the template provides the titlestring for the new activity

If youre using an I48 other than 8clipse add the new activitys title to the stringsxml fileamp

resources

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1516

string name+titleactivitydisplaymessageMy Messagestringresources

Add it to the $aniest

All activities must be declared in your manifest file AndroidManifestxml using an activity element

hen you use the 8clipse tools to create the activity it creates a default entry If youre usinga different I48 you need to add the manifest entry yourself It should loo lie thisamp

application activity androidampname+comexamplemyfirstapp4isplayMessageActivity androidamplabel+-stringtitleactivitydisplaymessage androidampparentActivityame+comexamplemyfirstappMainActivity meta$data androidampname+androidsupportEAgt8AI2Ilt

androidampvalue+comexamplemyfirstappMainActivity activityapplication

he androidampparentActivityame attribute declares the name of this activitys parent activitywithin the apps logical hierarchy he system uses this value to implement default navigationbehaviors such as Hp navigation on Android CF (AEI level F) and higher ltou can providethe same navigation behaviors for older versions of Android by using the upport Gibrary andadding the meta$data element as shown here

Note ltour Android 4D should already include the latest Android upport Gibrary Itsincluded with the A4 undle but if youre using a different I48 you should have installed it

during the Adding Elatforms and Eacages step hen using the templates in 8clipse theupport Gibrary is automatically added to your app pro0ect (you can see the librarys JAgt filelisted under Android Dependencies) If youre not using 8clipse you need to manually add thelibrary to your pro0ectKfollow the guide for setting up the upport Gibrary then return here

If youre developing with 8clipse you can run the app now but not much happens licingthe end button starts the second activity but it uses a default ello world layout providedby the template ltoull soon update the activity to instead display a custom text view so ifyoure using a different I48 dont worry that the app wont yet compile

Receive the Intent

8very Activity is invoed by an Intent regardless of how the user navigated there ltou can getthe Intent that started your activity by calling getIntent() and retrieve the data contained withinit

In the 4isplayMessageActivity classrsquos onreate() method get the intent and extract themessage delivered by MainActivityamp

Intent intent + getIntent()7tring message + intentgettring8xtra(MainActivity8gtAM8A8)7

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1616

(isplay the )essage

o show the message on the screen create a ext2iew widget and set the text usingsetext() hen add the ext2iew as the root view of the activityrsquos layout by passing it tosetontent2iew()

he complete onreate() method for 4isplayMessageActivity now loos lie thisamp

-verridepublic void onreate(undle savedInstancetate) 3 superonreate(savedInstancetate)7 et the message from the intent Intent intent + getIntent()7 tring message + intentgettring8xtra(MainActivity8gtAM8A8)7 reate the text view ext2iew text2iew + new ext2iew(this)7 text2iewsetextiBe(CL)7 text2iewsetext(message)7 et the text view as the activity layout setontent2iew(text2iew)7

5

ltou can now run the app hen it opens type a message in the text field clic end and themessage appears on the second activity

Figure oth activities in the final app running on Android CL

Page 4: 01 Building Your First App

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 416

src

Directory for your apps main source files 9y default it includes an Activity class that runs

when your app is launched using the app iconres

ontains seeral sudirectories for app resources 5ere are just a few

drawale-hdpi

Directory for drawale ojects (such as itmaps) that are designed for highdensity (hdpi)screens =ther drawale directories contain assets designed for other screen densitieslayo$t

Directory for files that define your apps user interface

val$es

Directory for other arious 18 files that contain a collection of resources such as string

and color definitions

Bhen you uild and run the default Android app the default Activity class starts and loads a layout

file that says 05ello Borld0 The result is nothing e4citing ut its important that you understand how

to run your app efore you start deeloping

un on a eal e(ice

f you hae a real Androidpowered deice heres how you can install and run your app

+lug in your deice to your deelopment machine with a ltS9 cale f youre deeloping on

Bindows you might need to install the appropriate ltS9 drier for your deice or helpinstalling driers see the =E1 ltS9 Driers document

$ Enale de-ugging on your deice

bull =n most deices running Android -$ or older you can find the option under ettings

Applications e(elopment

bull =n Android amp and newer its in ettings e(eloper options

Note =n Android $ and newer e(eloper options is hidden y default To make it

aailale go to ettings A-out phone and tap uild num-er seen times Ceturn to

the preious screen to find e(eloper options

To run the app from Eclipse

=pen one of your projects files and click un from the toolar

$ n the un as window that appears select Android Application and click $

Eclipse installs the app on your connected deice and starts it

=r to run your app from a command line

hange directories to the root of your Android project and e4ecuteant de$g

$ 1ake sure the Android SDK platorm-tools directory is included in your A

enironment ariale then e4ecute

ad install inMyFirstApp-de$gapk

- =n your deice locate MyFirstActivity and open it

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 516

Thats how you uild and run your Android app on a deiceF To start deeloping continue to the ne4t

lesson

un on the Emulator

Bhether youre using Eclipse or the command line to run your app on the emulator you need to first

create an Android 7irtual Deice (A7D) An A7D is a deice configuration for the Android emulator

that allows you to model different deices

Figure 1 The A7D 1anager showing a few irtual deices

To create an A7D

8aunch the Android 7irtual Deice 1anager

a n Eclipse click Android 7irtual Deice 1anager from the toolar

rom the command line change directories to ltsdkgttools and e4ecute

android avd

$ n the Android Virtual Device Manager panel click New

- ill in the details for the A7D 6ie it a name a platform target an SD card sie and a skin(576A is default)

lick Create A0

gt Select the new A7D from the Android Virtual Device Manager and click tart After the emulator oots up unlock the emulator screen

To run the app from Eclipse

=pen one of your projects files and click un from the toolar

$ n the un as window that appears select Android Application and click $

Eclipse installs the app on your A7D and starts it

=r to run your app from the command line

hange directories to the root of your Android project and e4ecute

ant de$g

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 616

$ 1ake sure the Android SDK platorm-tools directory is included in your A

enironment ariale then e4ecute

ad install inMyFirstApp-de$gapk

- =n the emulator locate MyFirstActivity and open it

uilding a imple ser nter2ace

The graphical user interface for an Android app is uilt using a hierarchy of iew and iewro$p

ojects iew ojects are usually lt widgets such as uttons or te4t fields and iewro$p ojects

are inisile iew containers that define how the child iews are laid out such as in a grid or a ertical

list

Android proides an 18 ocaulary that corresponds to the suclasses of iew and iewro$p so

you can define your lt in 18 using a hierarchy of lt elements

Alternati(e a)outs

Declaring your lt layout in 18 rather than runtime code is useful for seeral reasons ut its

especially important so you can create different layouts for different screen sies or e4ample you cancreate two ersions of a layout and tell the system to use one on 0small0 screens and the other on

0large0 screens or more information see the class aout Supporting Different Deices

Figure 1 llustration of how iewro$p ojects form ranches in the layout and contain other iew ojects

n this lesson youll create a layout in 18 that includes a te4t field and a utton n the followinglesson youll respond when the utton is pressed y sending the content of the te4t field to another

actiity

Create a inear a)out

=pen the activitymainxml file from the reslayo$t directory

Note n Eclipse when you open a layout file youre first shown the 6raphical 8ayout editor This is

an editor that helps you uild layouts using BSB6 tools or this lesson youre going to work

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 716

directly with the 18 so click the activity_mainxml ta at the ottom of the screen to open the 18

editor

The 9lankActiity template you chose when you created this project includes the

activitymainxml file with a 0elative1ayo$t root iew and a extiew child iew

irst delete the ltextiewgt element and change the lt0elative1ayo$tgt element to

lt1inear1ayo$tgt Then add the androidorientation attriute and set it to

)hori2ontal) The result looks like this

lt3xml version()+4) encoding()$t-)3gtlt1inear1ayo$t xmlnsandroid()httpschemasandroidcomapkresandroid) xmlnstools()httpschemasandroidcomtools) androidlayo$twidth()matchparent) androidlayo$theight()matchparent) androidorientation()hori2ontal) gtlt1inear1ayo$tgt

1inear1ayo$t is a iew group (a suclass of iewro$p) that lays out child iews in either a

ertical or horiontal orientation as specified y the androidorientation attriute Each child

of a 1inear1ayo$t appears on the screen in the order in which it appears in the 18The other two attriutes androidlayo$twidth and androidlayo$theight are

re3uired for all iews in order to specify their sie

9ecause the 1inear1ayo$t is the root iew in the layout it should fill the entire screen area thats

aailale to the app y setting the width and height to )matchparent) This alue declares that the

iew should e4pand its width or height to match the width or height of the parent iew

or more information aout layout properties see the 8ayout guide

Add a ext Field

To create a usereditale te4t field add an lt5ditextgt element inside the lt1inear1ayo$tgt

8ike eery iew oject you must define certain 18 attriutes to specify the 5ditext ojects

properties 5eres how you should declare it inside the lt1inear1ayo$tgt element

lt5ditext androidid()67ideditmessage) androidlayo$twidth()wrapcontent) androidlayo$theight()wrapcontent) androidhint()6stringeditmessage) gt

A-out resource o-jects

A resource oject is simply a uni3ue integer name thats associated with an app resource such as a itmap layout file or string

Eery resource has a corresponding resource oject defined in your projects gen0java file ou

can use the oject names in the 0 class to refer to your resources such as when you need to specify a

string alue for the androidhint attriute ou can also create aritrary resource Ds that you

associate with a iew using the androidid attriute which allows you to reference that iew from

other code

The SDK tools generate the 0java each time you compile your app ou should neer modify this

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 816

file y hand

or more information read the guide to +roiding Cesources

Aout these attriutes

androidid

This proides a uni3ue identifier for the iew which you can use to reference the oject from

your app code such as to read and manipulate the oject (youll see this in the ne4t lesson)

The at sign (6) is re3uired when youre referring to any resource oject from 18 t is followed

y the resource type (id in this case) a slash then the resource name (editmessage)

The plus sign (7) efore the resource type is needed only when youre defining a resource D for

the first time Bhen you compile the app the SDK tools use the D name to create a new

resource D in your projects gen0java file that refers to the 5ditext element =nce the

resource D is declared once this way other references to the D do not need the plus sign ltsing

the plus sign is necessary only when specifying a new resource D and not needed for concreteresources such as strings or layouts See the sideo4 for more information aout resource ojects

androidlayo$twidth and androidlayo$theight

nstead of using specific sies for the width and height the )wrapcontent) alue specifies

that the iew should e only as ig as needed to fit the contents of the iew f you were to

instead use )matchparent) then the 5ditext element would fill the screen ecause it

would match the sie of the parent 1inear1ayo$t or more information see the 8ayouts

guideandroidhint

This is a default string to display when the te4t field is empty nstead of using a hardcoded

string as the alue the )6stringeditmessage) alue refers to a string resource defined

in a separate file 9ecause this refers to a concrete resource (not just an identifier) it does not

need the plus sign 5oweer ecause you haent defined the string resource yet youll see acompiler error at first oull fi4 this in the ne4t section y defining the string

Note This string resource has the same name as the element D editmessage 5oweer

references to resources are always scoped y the resource type (such as id or string) so using

the same name does not cause collisions

Add tring esources

Bhen you need to add te4t in the user interface you should always specify each string as a resource

String resources allow you to manage all lt te4t in a single location which makes it easier to find and

update te4t E4ternaliing the strings also allows you to localie your app to different languages y proiding alternatie definitions for each string resource

9y default your Android project includes a string resource file at resval$esstringsxml

Add a new string named )editmessage) and set the alue to 0Enter a message0 (ou can delete

the 0helloGworld0 string)

Bhile youre in this file also add a 0Send0 string for the utton youll soon add called

)$ttonsend)

The result for stringsxml looks like this

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 916

lt3xml version()+4) encoding()$t-)3gtltreso$rcesgt ltstring name()appname)gtMy First Appltstringgt ltstring name()editmessage)gt5nter a messageltstringgt ltstring name()$ttonsend)gtampendltstringgt ltstring name()actionsettings)gtampettingsltstringgt ltstring name()titleactivitymain)gtMainActivityltstringgtltreso$rcesgt

or more information aout using string resources to localie your app for other languages see the

Supporting Different Deices class

Add a utton

ow add a lt8$ttongt to the layout immediately following the lt5ditextgt element

lt8$tton androidlayo$twidth()wrapcontent) androidlayo$theight()wrapcontent) androidtext()6string$ttonsend) gt

The height and width are set to )wrapcontent) so the utton is only as ig as necessary to fit the

uttons te4t This utton doesnt need the androidid attriute ecause it wont e referenced from

the actiity code

Make the nput ox Fill in the creen ampidth

The layout is currently designed so that oth the 5ditext and 8$tton widgets are only as ig as

necessary to fit their content as shown in figure $

Figure 3 The 5ditext and 8$tton widgets hae their widths set to )wrapcontent)

This works fine for the utton ut not as well for the te4t field ecause the user might type somethinglonger So it would e nice to fill the unused screen width with the te4t field ou can do this inside a

1inear1ayo$t with the weight property which you can specify using the

androidlayo$tweight attriute

The weight alue is a numer that specifies the amount of remaining space each iew should consume

relatie to the amount consumed y siling iews This works kind of like the amount of ingredients in

a drink recipe 0$ parts odka part coffee li3ueur0 means twothirds of the drink is odka ore4ample if you gie one iew a weight of $ and another one a weight of the sum is - so the firstiew fills $H- of the remaining space and the second iew fills the rest f you add a third iew and gie

it a weight of then the first iew (with weight of $) now gets H$ the remaining space while the

remaining two each get H

The default weight for all iews is amp so if you specify any weight alue greater than amp to only oneiew then that iew fills whateer space remains after all iews are gien the space they re3uire So to

fill the remaining space in your layout with the 5ditext element gie it a weight of and leae the

utton with no weight

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1016

lt5ditext androidlayo$tweight()+) gt

n order to improe the layout efficiency when you specify the weight you should change the width of

the 5ditext to e ero (ampdp) Setting the width to ero improes layout performance ecause using

)wrapcontent) as the width re3uires the system to calculate a width that is ultimately irreleant

ecause the weight alue re3uires another width calculation to fill the remaining space

lt5ditext androidlayo$tweight()+) androidlayo$twidth()4dp) gt

igure - shows the result when you assign all weight to the 5ditext element

Figure 4 The 5ditext widget is gien all the layout weight so fills the remaining space in the

1inear1ayo$t

5eres how your complete layout file should now look

lt3xml version()+4) encoding()$t-)3gtlt1inear1ayo$t xmlnsandroid()httpschemasandroidcomapkresandroid) xmlnstools()httpschemasandroidcomtools) androidlayo$twidth()matchparent) androidlayo$theight()matchparent) androidorientation()hori2ontal)gt lt5ditext androidid()67ideditmessage) androidlayo$tweight()+)

androidlayo$twidth()4dp) androidlayo$theight()wrapcontent) androidhint()6stringeditmessage) gt lt8$tton androidlayo$twidth()wrapcontent) androidlayo$theight()wrapcontent) androidtext()6string$ttonsend) gtlt1inear1ayo$tgt

This layout is applied y the default Activity class that the SDK tools generated when you created

the project so you can now run the app to see the results

bull n Eclipse click Cun from the toolar

bull =r from a command line change directories to the root of your Android project and e4ecute

ant de$gad install inMyFirstApp-de$gapk

ontinue to the ne4t lesson to learn how you can respond to utton presses read content from the te4t

field start another actiity and more

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1116

tarting Another Acti(it)

After completing the previous lesson you have an app that shows an activity (a single screen)with a text field and a button In this lesson yoursquoll add some code to MainActivity that starts anew activity when the user clics the end button

Respond to the Send Button

o respond to the buttons on$clic event open the activitymainxml layout file and add theandroidamponlic attribute to the utton elementamp

utton androidamplayoutwidth+wrapcontent androidamplayoutheight+wrapcontent androidamptext+-stringbuttonsend androidamponlic+sendMessage

he androidamponlic attributersquos value sendMessage is the name of a method in youractivity that the system calls when the user clics the button

pen the MainActivity class (located in the pro0ects src directory) and add the correspondingmethodamp

11 alled when the user clics the end button 1public void sendMessage(2iew view) 3 4o something in response to button5

his re6uires that you import the 2iew classamp

import androidview2iew7

Tip In 8clipse press trl 9 hift 9 to import missing classes (md 9 hift 9 on Mac)

In order for the system to match this method to the method name given to androidamponlicthe signature must be exactly as shown pecifically the method mustamp

bull e public

bull ave a void return value

bull ave a 2iew as the only parameter (this will be the 2iew that was cliced)

ext yoursquoll fill in this method to read the contents of the text field and deliver that text toanother activity

Build an Intent

An Intent is an ob0ect that provides runtime binding between separate components (such astwo activities) he Intent represents an apprsquos intent to do something ltou can use intentsfor a wide variety of tass but most often theyrsquore used to start another activity

Inside the sendMessage() method create an Intent to start an activity called4isplayMessageActivityamp

Intent intent + new Intent(this 4isplayMessageActivityclass)7

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1216

he constructor used here taes two parametersamp

bull A ontext as its first parameter (this is used because the Activity class is a subclass ofontext)

bull he lass of the app component to which the system should deliver the Intent (in thiscase the activity that should be started)

Sending an intent to other apps

he intent created in this lesson is whats considered an explicit intent because the Intent specifies the exact app component to which the intent should be given owever intents canalso be implicit in which case the Intent does not specify the desired component but allowsany app installed on the device to respond to the intent as long as it satisfies the meta$dataspecifications for the action thats specified in various Intent parameters =or moreinformation see the class about Interacting with ther Apps

Note he reference to 4isplayMessageActivity will raise an error if yoursquore using an I48 suchas 8clipse because the class doesnrsquot exist yet Ignore the error for now7 yoursquoll create the classsoon

An intent not only allows you to start another activity but it can carry a bundle of data to theactivity as well Inside the sendMessage() method use find2iewyId() to get the 8ditext element and add its text value to the intentamp

Intent intent + new Intent(this 4isplayMessageActivityclass)78ditext editext + (8ditext) find2iewyId(gtideditmessage)7tring message + editextgetext()totring()7intentput8xtra(8gtAM8A8 message)7

Note ltou now need import statements for androidcontentIntent andandroidwidget8ditext ltoull define the 8gtAM8A8 constant in a moment

An Intent can carry a collection of various data types as ey$value pairs called extras heput8xtra() method taes the ey name in the first parameter and the value in the secondparameter

In order for the next activity to 6uery the extra data you should define the ey for your intentsextra using a public constant o add the 8gtAM8A8 definition to the top of theMainActivity classamp

public class MainActivity extends Activity 3 public final static tring 8gtAM8A8 + comexamplemyfirstappM8A87 5

Its generally a good practice to define eys for intent extras using your apps pacage nameas a prefix his ensures they are uni6ue in case your app interacts with other apps

Start the Second Activity

o start an activity call startActivity() and pass it your Intent he system receives this call andstarts an instance of the Activity specified by the Intent

ith this new code the complete sendMessage() method thats invoed by the end button

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1316

now loos lie thisamp

11 alled when the user clics the end button 1public void sendMessage(2iew view) 3 Intent intent + new Intent(this 4isplayMessageActivityclass)7 8ditext editext + (8ditext) find2iewyId(gtideditmessage)7 tring message + editextgetext()totring()7 intentput8xtra(8gtAM8A8 message)7

startActivity(intent)75

ow you need to create the 4isplayMessageActivity class in order for this to wor

Create the Second Activity

Figure 1 he new activity wiBard in 8clipseo create a new activity using 8clipseamp

lic New in the toolbar$ In the window that appears open the Android folder and select Android Activity

lic Net- elect BlanActivity and clic NetC =ill in the activity detailsamp

bull roectamp My=irstApp

bull Activity Na$eamp 4isplayMessageActivity

bull ayout Na$eamp activitydisplaymessage

bull Titleamp My Messagebull ampierarchial arentamp comexamplemyfirstappMainActivity

bull Navigation Typeamp one

lic Finish

If youre using a different I48 or the command line tools create a new file named4isplayMessageActivity0ava in the pro0ects src directory next to the original MainActivity0avafile

pen the 4isplayMessageActivity0ava file If you used 8clipse to create this activityamp

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1416

bull he class already includes an implementation of the re6uired onreate() method

bull heres also an implementation of the onreateptionsMenu() method but you wontneed it for this app so you can remove it

bull heres also an implementation of onptionsItemelected() which handles thebehavior for the action bars Up behavior Deep this one the way it is

ecause the Actionar AEIs are available only on 8ltM (AEI level FF) and higher

you must add a condition around the getActionar() method to chec the current platformversion Additionally you must add the -uppressGint(ewApi) tag to the onreate() method to avoid lint errors

he 4isplayMessageActivity class should now loo lie thisamp

public class 4isplayMessageActivity extends Activity 3 -uppressGint(ewApi) -verride protected void onreate(undle savedInstancetate) 3 superonreate(savedInstancetate)7 setontent2iew(gtlayoutactivitydisplaymessage)7 Mae sure were running on oneycomb or higher to use Actionar AEIs

if (uild28gtI4DI + uild28gtI488ltM) 3 how the Hp button in the action bar getActionar()set4isplayomeAsHp8nabled(true)7 5 5 -verride public boolean onptionsItemelected(MenuItem item) 3 switch (itemgetItemId()) 3 case androidgtidhomeamp avHtilsnavigateHp=romameas(this)7 return true7 5 return superonptionsItemelected(item)7 55

If you used an I48 other than 8clipse update your 4isplayMessageActivity class with theabove code

All subclasses of Activity must implement the onreate() method he system calls this whencreating a new instance of the activity his method is where you must define the activitylayout with the setontent2iew() method and is where you should perform initial setup for theactivity components

Note If you are using an I48 other than 8clipse your pro0ect does not contain theactivitydisplaymessage layout thats re6uested by setontent2iew() hats D because

you will update this method later and wont be using that layout

Add the title string

If you used 8clipse you can sip to the next section because the template provides the titlestring for the new activity

If youre using an I48 other than 8clipse add the new activitys title to the stringsxml fileamp

resources

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1516

string name+titleactivitydisplaymessageMy Messagestringresources

Add it to the $aniest

All activities must be declared in your manifest file AndroidManifestxml using an activity element

hen you use the 8clipse tools to create the activity it creates a default entry If youre usinga different I48 you need to add the manifest entry yourself It should loo lie thisamp

application activity androidampname+comexamplemyfirstapp4isplayMessageActivity androidamplabel+-stringtitleactivitydisplaymessage androidampparentActivityame+comexamplemyfirstappMainActivity meta$data androidampname+androidsupportEAgt8AI2Ilt

androidampvalue+comexamplemyfirstappMainActivity activityapplication

he androidampparentActivityame attribute declares the name of this activitys parent activitywithin the apps logical hierarchy he system uses this value to implement default navigationbehaviors such as Hp navigation on Android CF (AEI level F) and higher ltou can providethe same navigation behaviors for older versions of Android by using the upport Gibrary andadding the meta$data element as shown here

Note ltour Android 4D should already include the latest Android upport Gibrary Itsincluded with the A4 undle but if youre using a different I48 you should have installed it

during the Adding Elatforms and Eacages step hen using the templates in 8clipse theupport Gibrary is automatically added to your app pro0ect (you can see the librarys JAgt filelisted under Android Dependencies) If youre not using 8clipse you need to manually add thelibrary to your pro0ectKfollow the guide for setting up the upport Gibrary then return here

If youre developing with 8clipse you can run the app now but not much happens licingthe end button starts the second activity but it uses a default ello world layout providedby the template ltoull soon update the activity to instead display a custom text view so ifyoure using a different I48 dont worry that the app wont yet compile

Receive the Intent

8very Activity is invoed by an Intent regardless of how the user navigated there ltou can getthe Intent that started your activity by calling getIntent() and retrieve the data contained withinit

In the 4isplayMessageActivity classrsquos onreate() method get the intent and extract themessage delivered by MainActivityamp

Intent intent + getIntent()7tring message + intentgettring8xtra(MainActivity8gtAM8A8)7

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1616

(isplay the )essage

o show the message on the screen create a ext2iew widget and set the text usingsetext() hen add the ext2iew as the root view of the activityrsquos layout by passing it tosetontent2iew()

he complete onreate() method for 4isplayMessageActivity now loos lie thisamp

-verridepublic void onreate(undle savedInstancetate) 3 superonreate(savedInstancetate)7 et the message from the intent Intent intent + getIntent()7 tring message + intentgettring8xtra(MainActivity8gtAM8A8)7 reate the text view ext2iew text2iew + new ext2iew(this)7 text2iewsetextiBe(CL)7 text2iewsetext(message)7 et the text view as the activity layout setontent2iew(text2iew)7

5

ltou can now run the app hen it opens type a message in the text field clic end and themessage appears on the second activity

Figure oth activities in the final app running on Android CL

Page 5: 01 Building Your First App

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 516

Thats how you uild and run your Android app on a deiceF To start deeloping continue to the ne4t

lesson

un on the Emulator

Bhether youre using Eclipse or the command line to run your app on the emulator you need to first

create an Android 7irtual Deice (A7D) An A7D is a deice configuration for the Android emulator

that allows you to model different deices

Figure 1 The A7D 1anager showing a few irtual deices

To create an A7D

8aunch the Android 7irtual Deice 1anager

a n Eclipse click Android 7irtual Deice 1anager from the toolar

rom the command line change directories to ltsdkgttools and e4ecute

android avd

$ n the Android Virtual Device Manager panel click New

- ill in the details for the A7D 6ie it a name a platform target an SD card sie and a skin(576A is default)

lick Create A0

gt Select the new A7D from the Android Virtual Device Manager and click tart After the emulator oots up unlock the emulator screen

To run the app from Eclipse

=pen one of your projects files and click un from the toolar

$ n the un as window that appears select Android Application and click $

Eclipse installs the app on your A7D and starts it

=r to run your app from the command line

hange directories to the root of your Android project and e4ecute

ant de$g

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 616

$ 1ake sure the Android SDK platorm-tools directory is included in your A

enironment ariale then e4ecute

ad install inMyFirstApp-de$gapk

- =n the emulator locate MyFirstActivity and open it

uilding a imple ser nter2ace

The graphical user interface for an Android app is uilt using a hierarchy of iew and iewro$p

ojects iew ojects are usually lt widgets such as uttons or te4t fields and iewro$p ojects

are inisile iew containers that define how the child iews are laid out such as in a grid or a ertical

list

Android proides an 18 ocaulary that corresponds to the suclasses of iew and iewro$p so

you can define your lt in 18 using a hierarchy of lt elements

Alternati(e a)outs

Declaring your lt layout in 18 rather than runtime code is useful for seeral reasons ut its

especially important so you can create different layouts for different screen sies or e4ample you cancreate two ersions of a layout and tell the system to use one on 0small0 screens and the other on

0large0 screens or more information see the class aout Supporting Different Deices

Figure 1 llustration of how iewro$p ojects form ranches in the layout and contain other iew ojects

n this lesson youll create a layout in 18 that includes a te4t field and a utton n the followinglesson youll respond when the utton is pressed y sending the content of the te4t field to another

actiity

Create a inear a)out

=pen the activitymainxml file from the reslayo$t directory

Note n Eclipse when you open a layout file youre first shown the 6raphical 8ayout editor This is

an editor that helps you uild layouts using BSB6 tools or this lesson youre going to work

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 716

directly with the 18 so click the activity_mainxml ta at the ottom of the screen to open the 18

editor

The 9lankActiity template you chose when you created this project includes the

activitymainxml file with a 0elative1ayo$t root iew and a extiew child iew

irst delete the ltextiewgt element and change the lt0elative1ayo$tgt element to

lt1inear1ayo$tgt Then add the androidorientation attriute and set it to

)hori2ontal) The result looks like this

lt3xml version()+4) encoding()$t-)3gtlt1inear1ayo$t xmlnsandroid()httpschemasandroidcomapkresandroid) xmlnstools()httpschemasandroidcomtools) androidlayo$twidth()matchparent) androidlayo$theight()matchparent) androidorientation()hori2ontal) gtlt1inear1ayo$tgt

1inear1ayo$t is a iew group (a suclass of iewro$p) that lays out child iews in either a

ertical or horiontal orientation as specified y the androidorientation attriute Each child

of a 1inear1ayo$t appears on the screen in the order in which it appears in the 18The other two attriutes androidlayo$twidth and androidlayo$theight are

re3uired for all iews in order to specify their sie

9ecause the 1inear1ayo$t is the root iew in the layout it should fill the entire screen area thats

aailale to the app y setting the width and height to )matchparent) This alue declares that the

iew should e4pand its width or height to match the width or height of the parent iew

or more information aout layout properties see the 8ayout guide

Add a ext Field

To create a usereditale te4t field add an lt5ditextgt element inside the lt1inear1ayo$tgt

8ike eery iew oject you must define certain 18 attriutes to specify the 5ditext ojects

properties 5eres how you should declare it inside the lt1inear1ayo$tgt element

lt5ditext androidid()67ideditmessage) androidlayo$twidth()wrapcontent) androidlayo$theight()wrapcontent) androidhint()6stringeditmessage) gt

A-out resource o-jects

A resource oject is simply a uni3ue integer name thats associated with an app resource such as a itmap layout file or string

Eery resource has a corresponding resource oject defined in your projects gen0java file ou

can use the oject names in the 0 class to refer to your resources such as when you need to specify a

string alue for the androidhint attriute ou can also create aritrary resource Ds that you

associate with a iew using the androidid attriute which allows you to reference that iew from

other code

The SDK tools generate the 0java each time you compile your app ou should neer modify this

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 816

file y hand

or more information read the guide to +roiding Cesources

Aout these attriutes

androidid

This proides a uni3ue identifier for the iew which you can use to reference the oject from

your app code such as to read and manipulate the oject (youll see this in the ne4t lesson)

The at sign (6) is re3uired when youre referring to any resource oject from 18 t is followed

y the resource type (id in this case) a slash then the resource name (editmessage)

The plus sign (7) efore the resource type is needed only when youre defining a resource D for

the first time Bhen you compile the app the SDK tools use the D name to create a new

resource D in your projects gen0java file that refers to the 5ditext element =nce the

resource D is declared once this way other references to the D do not need the plus sign ltsing

the plus sign is necessary only when specifying a new resource D and not needed for concreteresources such as strings or layouts See the sideo4 for more information aout resource ojects

androidlayo$twidth and androidlayo$theight

nstead of using specific sies for the width and height the )wrapcontent) alue specifies

that the iew should e only as ig as needed to fit the contents of the iew f you were to

instead use )matchparent) then the 5ditext element would fill the screen ecause it

would match the sie of the parent 1inear1ayo$t or more information see the 8ayouts

guideandroidhint

This is a default string to display when the te4t field is empty nstead of using a hardcoded

string as the alue the )6stringeditmessage) alue refers to a string resource defined

in a separate file 9ecause this refers to a concrete resource (not just an identifier) it does not

need the plus sign 5oweer ecause you haent defined the string resource yet youll see acompiler error at first oull fi4 this in the ne4t section y defining the string

Note This string resource has the same name as the element D editmessage 5oweer

references to resources are always scoped y the resource type (such as id or string) so using

the same name does not cause collisions

Add tring esources

Bhen you need to add te4t in the user interface you should always specify each string as a resource

String resources allow you to manage all lt te4t in a single location which makes it easier to find and

update te4t E4ternaliing the strings also allows you to localie your app to different languages y proiding alternatie definitions for each string resource

9y default your Android project includes a string resource file at resval$esstringsxml

Add a new string named )editmessage) and set the alue to 0Enter a message0 (ou can delete

the 0helloGworld0 string)

Bhile youre in this file also add a 0Send0 string for the utton youll soon add called

)$ttonsend)

The result for stringsxml looks like this

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 916

lt3xml version()+4) encoding()$t-)3gtltreso$rcesgt ltstring name()appname)gtMy First Appltstringgt ltstring name()editmessage)gt5nter a messageltstringgt ltstring name()$ttonsend)gtampendltstringgt ltstring name()actionsettings)gtampettingsltstringgt ltstring name()titleactivitymain)gtMainActivityltstringgtltreso$rcesgt

or more information aout using string resources to localie your app for other languages see the

Supporting Different Deices class

Add a utton

ow add a lt8$ttongt to the layout immediately following the lt5ditextgt element

lt8$tton androidlayo$twidth()wrapcontent) androidlayo$theight()wrapcontent) androidtext()6string$ttonsend) gt

The height and width are set to )wrapcontent) so the utton is only as ig as necessary to fit the

uttons te4t This utton doesnt need the androidid attriute ecause it wont e referenced from

the actiity code

Make the nput ox Fill in the creen ampidth

The layout is currently designed so that oth the 5ditext and 8$tton widgets are only as ig as

necessary to fit their content as shown in figure $

Figure 3 The 5ditext and 8$tton widgets hae their widths set to )wrapcontent)

This works fine for the utton ut not as well for the te4t field ecause the user might type somethinglonger So it would e nice to fill the unused screen width with the te4t field ou can do this inside a

1inear1ayo$t with the weight property which you can specify using the

androidlayo$tweight attriute

The weight alue is a numer that specifies the amount of remaining space each iew should consume

relatie to the amount consumed y siling iews This works kind of like the amount of ingredients in

a drink recipe 0$ parts odka part coffee li3ueur0 means twothirds of the drink is odka ore4ample if you gie one iew a weight of $ and another one a weight of the sum is - so the firstiew fills $H- of the remaining space and the second iew fills the rest f you add a third iew and gie

it a weight of then the first iew (with weight of $) now gets H$ the remaining space while the

remaining two each get H

The default weight for all iews is amp so if you specify any weight alue greater than amp to only oneiew then that iew fills whateer space remains after all iews are gien the space they re3uire So to

fill the remaining space in your layout with the 5ditext element gie it a weight of and leae the

utton with no weight

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1016

lt5ditext androidlayo$tweight()+) gt

n order to improe the layout efficiency when you specify the weight you should change the width of

the 5ditext to e ero (ampdp) Setting the width to ero improes layout performance ecause using

)wrapcontent) as the width re3uires the system to calculate a width that is ultimately irreleant

ecause the weight alue re3uires another width calculation to fill the remaining space

lt5ditext androidlayo$tweight()+) androidlayo$twidth()4dp) gt

igure - shows the result when you assign all weight to the 5ditext element

Figure 4 The 5ditext widget is gien all the layout weight so fills the remaining space in the

1inear1ayo$t

5eres how your complete layout file should now look

lt3xml version()+4) encoding()$t-)3gtlt1inear1ayo$t xmlnsandroid()httpschemasandroidcomapkresandroid) xmlnstools()httpschemasandroidcomtools) androidlayo$twidth()matchparent) androidlayo$theight()matchparent) androidorientation()hori2ontal)gt lt5ditext androidid()67ideditmessage) androidlayo$tweight()+)

androidlayo$twidth()4dp) androidlayo$theight()wrapcontent) androidhint()6stringeditmessage) gt lt8$tton androidlayo$twidth()wrapcontent) androidlayo$theight()wrapcontent) androidtext()6string$ttonsend) gtlt1inear1ayo$tgt

This layout is applied y the default Activity class that the SDK tools generated when you created

the project so you can now run the app to see the results

bull n Eclipse click Cun from the toolar

bull =r from a command line change directories to the root of your Android project and e4ecute

ant de$gad install inMyFirstApp-de$gapk

ontinue to the ne4t lesson to learn how you can respond to utton presses read content from the te4t

field start another actiity and more

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1116

tarting Another Acti(it)

After completing the previous lesson you have an app that shows an activity (a single screen)with a text field and a button In this lesson yoursquoll add some code to MainActivity that starts anew activity when the user clics the end button

Respond to the Send Button

o respond to the buttons on$clic event open the activitymainxml layout file and add theandroidamponlic attribute to the utton elementamp

utton androidamplayoutwidth+wrapcontent androidamplayoutheight+wrapcontent androidamptext+-stringbuttonsend androidamponlic+sendMessage

he androidamponlic attributersquos value sendMessage is the name of a method in youractivity that the system calls when the user clics the button

pen the MainActivity class (located in the pro0ects src directory) and add the correspondingmethodamp

11 alled when the user clics the end button 1public void sendMessage(2iew view) 3 4o something in response to button5

his re6uires that you import the 2iew classamp

import androidview2iew7

Tip In 8clipse press trl 9 hift 9 to import missing classes (md 9 hift 9 on Mac)

In order for the system to match this method to the method name given to androidamponlicthe signature must be exactly as shown pecifically the method mustamp

bull e public

bull ave a void return value

bull ave a 2iew as the only parameter (this will be the 2iew that was cliced)

ext yoursquoll fill in this method to read the contents of the text field and deliver that text toanother activity

Build an Intent

An Intent is an ob0ect that provides runtime binding between separate components (such astwo activities) he Intent represents an apprsquos intent to do something ltou can use intentsfor a wide variety of tass but most often theyrsquore used to start another activity

Inside the sendMessage() method create an Intent to start an activity called4isplayMessageActivityamp

Intent intent + new Intent(this 4isplayMessageActivityclass)7

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1216

he constructor used here taes two parametersamp

bull A ontext as its first parameter (this is used because the Activity class is a subclass ofontext)

bull he lass of the app component to which the system should deliver the Intent (in thiscase the activity that should be started)

Sending an intent to other apps

he intent created in this lesson is whats considered an explicit intent because the Intent specifies the exact app component to which the intent should be given owever intents canalso be implicit in which case the Intent does not specify the desired component but allowsany app installed on the device to respond to the intent as long as it satisfies the meta$dataspecifications for the action thats specified in various Intent parameters =or moreinformation see the class about Interacting with ther Apps

Note he reference to 4isplayMessageActivity will raise an error if yoursquore using an I48 suchas 8clipse because the class doesnrsquot exist yet Ignore the error for now7 yoursquoll create the classsoon

An intent not only allows you to start another activity but it can carry a bundle of data to theactivity as well Inside the sendMessage() method use find2iewyId() to get the 8ditext element and add its text value to the intentamp

Intent intent + new Intent(this 4isplayMessageActivityclass)78ditext editext + (8ditext) find2iewyId(gtideditmessage)7tring message + editextgetext()totring()7intentput8xtra(8gtAM8A8 message)7

Note ltou now need import statements for androidcontentIntent andandroidwidget8ditext ltoull define the 8gtAM8A8 constant in a moment

An Intent can carry a collection of various data types as ey$value pairs called extras heput8xtra() method taes the ey name in the first parameter and the value in the secondparameter

In order for the next activity to 6uery the extra data you should define the ey for your intentsextra using a public constant o add the 8gtAM8A8 definition to the top of theMainActivity classamp

public class MainActivity extends Activity 3 public final static tring 8gtAM8A8 + comexamplemyfirstappM8A87 5

Its generally a good practice to define eys for intent extras using your apps pacage nameas a prefix his ensures they are uni6ue in case your app interacts with other apps

Start the Second Activity

o start an activity call startActivity() and pass it your Intent he system receives this call andstarts an instance of the Activity specified by the Intent

ith this new code the complete sendMessage() method thats invoed by the end button

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1316

now loos lie thisamp

11 alled when the user clics the end button 1public void sendMessage(2iew view) 3 Intent intent + new Intent(this 4isplayMessageActivityclass)7 8ditext editext + (8ditext) find2iewyId(gtideditmessage)7 tring message + editextgetext()totring()7 intentput8xtra(8gtAM8A8 message)7

startActivity(intent)75

ow you need to create the 4isplayMessageActivity class in order for this to wor

Create the Second Activity

Figure 1 he new activity wiBard in 8clipseo create a new activity using 8clipseamp

lic New in the toolbar$ In the window that appears open the Android folder and select Android Activity

lic Net- elect BlanActivity and clic NetC =ill in the activity detailsamp

bull roectamp My=irstApp

bull Activity Na$eamp 4isplayMessageActivity

bull ayout Na$eamp activitydisplaymessage

bull Titleamp My Messagebull ampierarchial arentamp comexamplemyfirstappMainActivity

bull Navigation Typeamp one

lic Finish

If youre using a different I48 or the command line tools create a new file named4isplayMessageActivity0ava in the pro0ects src directory next to the original MainActivity0avafile

pen the 4isplayMessageActivity0ava file If you used 8clipse to create this activityamp

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1416

bull he class already includes an implementation of the re6uired onreate() method

bull heres also an implementation of the onreateptionsMenu() method but you wontneed it for this app so you can remove it

bull heres also an implementation of onptionsItemelected() which handles thebehavior for the action bars Up behavior Deep this one the way it is

ecause the Actionar AEIs are available only on 8ltM (AEI level FF) and higher

you must add a condition around the getActionar() method to chec the current platformversion Additionally you must add the -uppressGint(ewApi) tag to the onreate() method to avoid lint errors

he 4isplayMessageActivity class should now loo lie thisamp

public class 4isplayMessageActivity extends Activity 3 -uppressGint(ewApi) -verride protected void onreate(undle savedInstancetate) 3 superonreate(savedInstancetate)7 setontent2iew(gtlayoutactivitydisplaymessage)7 Mae sure were running on oneycomb or higher to use Actionar AEIs

if (uild28gtI4DI + uild28gtI488ltM) 3 how the Hp button in the action bar getActionar()set4isplayomeAsHp8nabled(true)7 5 5 -verride public boolean onptionsItemelected(MenuItem item) 3 switch (itemgetItemId()) 3 case androidgtidhomeamp avHtilsnavigateHp=romameas(this)7 return true7 5 return superonptionsItemelected(item)7 55

If you used an I48 other than 8clipse update your 4isplayMessageActivity class with theabove code

All subclasses of Activity must implement the onreate() method he system calls this whencreating a new instance of the activity his method is where you must define the activitylayout with the setontent2iew() method and is where you should perform initial setup for theactivity components

Note If you are using an I48 other than 8clipse your pro0ect does not contain theactivitydisplaymessage layout thats re6uested by setontent2iew() hats D because

you will update this method later and wont be using that layout

Add the title string

If you used 8clipse you can sip to the next section because the template provides the titlestring for the new activity

If youre using an I48 other than 8clipse add the new activitys title to the stringsxml fileamp

resources

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1516

string name+titleactivitydisplaymessageMy Messagestringresources

Add it to the $aniest

All activities must be declared in your manifest file AndroidManifestxml using an activity element

hen you use the 8clipse tools to create the activity it creates a default entry If youre usinga different I48 you need to add the manifest entry yourself It should loo lie thisamp

application activity androidampname+comexamplemyfirstapp4isplayMessageActivity androidamplabel+-stringtitleactivitydisplaymessage androidampparentActivityame+comexamplemyfirstappMainActivity meta$data androidampname+androidsupportEAgt8AI2Ilt

androidampvalue+comexamplemyfirstappMainActivity activityapplication

he androidampparentActivityame attribute declares the name of this activitys parent activitywithin the apps logical hierarchy he system uses this value to implement default navigationbehaviors such as Hp navigation on Android CF (AEI level F) and higher ltou can providethe same navigation behaviors for older versions of Android by using the upport Gibrary andadding the meta$data element as shown here

Note ltour Android 4D should already include the latest Android upport Gibrary Itsincluded with the A4 undle but if youre using a different I48 you should have installed it

during the Adding Elatforms and Eacages step hen using the templates in 8clipse theupport Gibrary is automatically added to your app pro0ect (you can see the librarys JAgt filelisted under Android Dependencies) If youre not using 8clipse you need to manually add thelibrary to your pro0ectKfollow the guide for setting up the upport Gibrary then return here

If youre developing with 8clipse you can run the app now but not much happens licingthe end button starts the second activity but it uses a default ello world layout providedby the template ltoull soon update the activity to instead display a custom text view so ifyoure using a different I48 dont worry that the app wont yet compile

Receive the Intent

8very Activity is invoed by an Intent regardless of how the user navigated there ltou can getthe Intent that started your activity by calling getIntent() and retrieve the data contained withinit

In the 4isplayMessageActivity classrsquos onreate() method get the intent and extract themessage delivered by MainActivityamp

Intent intent + getIntent()7tring message + intentgettring8xtra(MainActivity8gtAM8A8)7

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1616

(isplay the )essage

o show the message on the screen create a ext2iew widget and set the text usingsetext() hen add the ext2iew as the root view of the activityrsquos layout by passing it tosetontent2iew()

he complete onreate() method for 4isplayMessageActivity now loos lie thisamp

-verridepublic void onreate(undle savedInstancetate) 3 superonreate(savedInstancetate)7 et the message from the intent Intent intent + getIntent()7 tring message + intentgettring8xtra(MainActivity8gtAM8A8)7 reate the text view ext2iew text2iew + new ext2iew(this)7 text2iewsetextiBe(CL)7 text2iewsetext(message)7 et the text view as the activity layout setontent2iew(text2iew)7

5

ltou can now run the app hen it opens type a message in the text field clic end and themessage appears on the second activity

Figure oth activities in the final app running on Android CL

Page 6: 01 Building Your First App

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 616

$ 1ake sure the Android SDK platorm-tools directory is included in your A

enironment ariale then e4ecute

ad install inMyFirstApp-de$gapk

- =n the emulator locate MyFirstActivity and open it

uilding a imple ser nter2ace

The graphical user interface for an Android app is uilt using a hierarchy of iew and iewro$p

ojects iew ojects are usually lt widgets such as uttons or te4t fields and iewro$p ojects

are inisile iew containers that define how the child iews are laid out such as in a grid or a ertical

list

Android proides an 18 ocaulary that corresponds to the suclasses of iew and iewro$p so

you can define your lt in 18 using a hierarchy of lt elements

Alternati(e a)outs

Declaring your lt layout in 18 rather than runtime code is useful for seeral reasons ut its

especially important so you can create different layouts for different screen sies or e4ample you cancreate two ersions of a layout and tell the system to use one on 0small0 screens and the other on

0large0 screens or more information see the class aout Supporting Different Deices

Figure 1 llustration of how iewro$p ojects form ranches in the layout and contain other iew ojects

n this lesson youll create a layout in 18 that includes a te4t field and a utton n the followinglesson youll respond when the utton is pressed y sending the content of the te4t field to another

actiity

Create a inear a)out

=pen the activitymainxml file from the reslayo$t directory

Note n Eclipse when you open a layout file youre first shown the 6raphical 8ayout editor This is

an editor that helps you uild layouts using BSB6 tools or this lesson youre going to work

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 716

directly with the 18 so click the activity_mainxml ta at the ottom of the screen to open the 18

editor

The 9lankActiity template you chose when you created this project includes the

activitymainxml file with a 0elative1ayo$t root iew and a extiew child iew

irst delete the ltextiewgt element and change the lt0elative1ayo$tgt element to

lt1inear1ayo$tgt Then add the androidorientation attriute and set it to

)hori2ontal) The result looks like this

lt3xml version()+4) encoding()$t-)3gtlt1inear1ayo$t xmlnsandroid()httpschemasandroidcomapkresandroid) xmlnstools()httpschemasandroidcomtools) androidlayo$twidth()matchparent) androidlayo$theight()matchparent) androidorientation()hori2ontal) gtlt1inear1ayo$tgt

1inear1ayo$t is a iew group (a suclass of iewro$p) that lays out child iews in either a

ertical or horiontal orientation as specified y the androidorientation attriute Each child

of a 1inear1ayo$t appears on the screen in the order in which it appears in the 18The other two attriutes androidlayo$twidth and androidlayo$theight are

re3uired for all iews in order to specify their sie

9ecause the 1inear1ayo$t is the root iew in the layout it should fill the entire screen area thats

aailale to the app y setting the width and height to )matchparent) This alue declares that the

iew should e4pand its width or height to match the width or height of the parent iew

or more information aout layout properties see the 8ayout guide

Add a ext Field

To create a usereditale te4t field add an lt5ditextgt element inside the lt1inear1ayo$tgt

8ike eery iew oject you must define certain 18 attriutes to specify the 5ditext ojects

properties 5eres how you should declare it inside the lt1inear1ayo$tgt element

lt5ditext androidid()67ideditmessage) androidlayo$twidth()wrapcontent) androidlayo$theight()wrapcontent) androidhint()6stringeditmessage) gt

A-out resource o-jects

A resource oject is simply a uni3ue integer name thats associated with an app resource such as a itmap layout file or string

Eery resource has a corresponding resource oject defined in your projects gen0java file ou

can use the oject names in the 0 class to refer to your resources such as when you need to specify a

string alue for the androidhint attriute ou can also create aritrary resource Ds that you

associate with a iew using the androidid attriute which allows you to reference that iew from

other code

The SDK tools generate the 0java each time you compile your app ou should neer modify this

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 816

file y hand

or more information read the guide to +roiding Cesources

Aout these attriutes

androidid

This proides a uni3ue identifier for the iew which you can use to reference the oject from

your app code such as to read and manipulate the oject (youll see this in the ne4t lesson)

The at sign (6) is re3uired when youre referring to any resource oject from 18 t is followed

y the resource type (id in this case) a slash then the resource name (editmessage)

The plus sign (7) efore the resource type is needed only when youre defining a resource D for

the first time Bhen you compile the app the SDK tools use the D name to create a new

resource D in your projects gen0java file that refers to the 5ditext element =nce the

resource D is declared once this way other references to the D do not need the plus sign ltsing

the plus sign is necessary only when specifying a new resource D and not needed for concreteresources such as strings or layouts See the sideo4 for more information aout resource ojects

androidlayo$twidth and androidlayo$theight

nstead of using specific sies for the width and height the )wrapcontent) alue specifies

that the iew should e only as ig as needed to fit the contents of the iew f you were to

instead use )matchparent) then the 5ditext element would fill the screen ecause it

would match the sie of the parent 1inear1ayo$t or more information see the 8ayouts

guideandroidhint

This is a default string to display when the te4t field is empty nstead of using a hardcoded

string as the alue the )6stringeditmessage) alue refers to a string resource defined

in a separate file 9ecause this refers to a concrete resource (not just an identifier) it does not

need the plus sign 5oweer ecause you haent defined the string resource yet youll see acompiler error at first oull fi4 this in the ne4t section y defining the string

Note This string resource has the same name as the element D editmessage 5oweer

references to resources are always scoped y the resource type (such as id or string) so using

the same name does not cause collisions

Add tring esources

Bhen you need to add te4t in the user interface you should always specify each string as a resource

String resources allow you to manage all lt te4t in a single location which makes it easier to find and

update te4t E4ternaliing the strings also allows you to localie your app to different languages y proiding alternatie definitions for each string resource

9y default your Android project includes a string resource file at resval$esstringsxml

Add a new string named )editmessage) and set the alue to 0Enter a message0 (ou can delete

the 0helloGworld0 string)

Bhile youre in this file also add a 0Send0 string for the utton youll soon add called

)$ttonsend)

The result for stringsxml looks like this

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 916

lt3xml version()+4) encoding()$t-)3gtltreso$rcesgt ltstring name()appname)gtMy First Appltstringgt ltstring name()editmessage)gt5nter a messageltstringgt ltstring name()$ttonsend)gtampendltstringgt ltstring name()actionsettings)gtampettingsltstringgt ltstring name()titleactivitymain)gtMainActivityltstringgtltreso$rcesgt

or more information aout using string resources to localie your app for other languages see the

Supporting Different Deices class

Add a utton

ow add a lt8$ttongt to the layout immediately following the lt5ditextgt element

lt8$tton androidlayo$twidth()wrapcontent) androidlayo$theight()wrapcontent) androidtext()6string$ttonsend) gt

The height and width are set to )wrapcontent) so the utton is only as ig as necessary to fit the

uttons te4t This utton doesnt need the androidid attriute ecause it wont e referenced from

the actiity code

Make the nput ox Fill in the creen ampidth

The layout is currently designed so that oth the 5ditext and 8$tton widgets are only as ig as

necessary to fit their content as shown in figure $

Figure 3 The 5ditext and 8$tton widgets hae their widths set to )wrapcontent)

This works fine for the utton ut not as well for the te4t field ecause the user might type somethinglonger So it would e nice to fill the unused screen width with the te4t field ou can do this inside a

1inear1ayo$t with the weight property which you can specify using the

androidlayo$tweight attriute

The weight alue is a numer that specifies the amount of remaining space each iew should consume

relatie to the amount consumed y siling iews This works kind of like the amount of ingredients in

a drink recipe 0$ parts odka part coffee li3ueur0 means twothirds of the drink is odka ore4ample if you gie one iew a weight of $ and another one a weight of the sum is - so the firstiew fills $H- of the remaining space and the second iew fills the rest f you add a third iew and gie

it a weight of then the first iew (with weight of $) now gets H$ the remaining space while the

remaining two each get H

The default weight for all iews is amp so if you specify any weight alue greater than amp to only oneiew then that iew fills whateer space remains after all iews are gien the space they re3uire So to

fill the remaining space in your layout with the 5ditext element gie it a weight of and leae the

utton with no weight

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1016

lt5ditext androidlayo$tweight()+) gt

n order to improe the layout efficiency when you specify the weight you should change the width of

the 5ditext to e ero (ampdp) Setting the width to ero improes layout performance ecause using

)wrapcontent) as the width re3uires the system to calculate a width that is ultimately irreleant

ecause the weight alue re3uires another width calculation to fill the remaining space

lt5ditext androidlayo$tweight()+) androidlayo$twidth()4dp) gt

igure - shows the result when you assign all weight to the 5ditext element

Figure 4 The 5ditext widget is gien all the layout weight so fills the remaining space in the

1inear1ayo$t

5eres how your complete layout file should now look

lt3xml version()+4) encoding()$t-)3gtlt1inear1ayo$t xmlnsandroid()httpschemasandroidcomapkresandroid) xmlnstools()httpschemasandroidcomtools) androidlayo$twidth()matchparent) androidlayo$theight()matchparent) androidorientation()hori2ontal)gt lt5ditext androidid()67ideditmessage) androidlayo$tweight()+)

androidlayo$twidth()4dp) androidlayo$theight()wrapcontent) androidhint()6stringeditmessage) gt lt8$tton androidlayo$twidth()wrapcontent) androidlayo$theight()wrapcontent) androidtext()6string$ttonsend) gtlt1inear1ayo$tgt

This layout is applied y the default Activity class that the SDK tools generated when you created

the project so you can now run the app to see the results

bull n Eclipse click Cun from the toolar

bull =r from a command line change directories to the root of your Android project and e4ecute

ant de$gad install inMyFirstApp-de$gapk

ontinue to the ne4t lesson to learn how you can respond to utton presses read content from the te4t

field start another actiity and more

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1116

tarting Another Acti(it)

After completing the previous lesson you have an app that shows an activity (a single screen)with a text field and a button In this lesson yoursquoll add some code to MainActivity that starts anew activity when the user clics the end button

Respond to the Send Button

o respond to the buttons on$clic event open the activitymainxml layout file and add theandroidamponlic attribute to the utton elementamp

utton androidamplayoutwidth+wrapcontent androidamplayoutheight+wrapcontent androidamptext+-stringbuttonsend androidamponlic+sendMessage

he androidamponlic attributersquos value sendMessage is the name of a method in youractivity that the system calls when the user clics the button

pen the MainActivity class (located in the pro0ects src directory) and add the correspondingmethodamp

11 alled when the user clics the end button 1public void sendMessage(2iew view) 3 4o something in response to button5

his re6uires that you import the 2iew classamp

import androidview2iew7

Tip In 8clipse press trl 9 hift 9 to import missing classes (md 9 hift 9 on Mac)

In order for the system to match this method to the method name given to androidamponlicthe signature must be exactly as shown pecifically the method mustamp

bull e public

bull ave a void return value

bull ave a 2iew as the only parameter (this will be the 2iew that was cliced)

ext yoursquoll fill in this method to read the contents of the text field and deliver that text toanother activity

Build an Intent

An Intent is an ob0ect that provides runtime binding between separate components (such astwo activities) he Intent represents an apprsquos intent to do something ltou can use intentsfor a wide variety of tass but most often theyrsquore used to start another activity

Inside the sendMessage() method create an Intent to start an activity called4isplayMessageActivityamp

Intent intent + new Intent(this 4isplayMessageActivityclass)7

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1216

he constructor used here taes two parametersamp

bull A ontext as its first parameter (this is used because the Activity class is a subclass ofontext)

bull he lass of the app component to which the system should deliver the Intent (in thiscase the activity that should be started)

Sending an intent to other apps

he intent created in this lesson is whats considered an explicit intent because the Intent specifies the exact app component to which the intent should be given owever intents canalso be implicit in which case the Intent does not specify the desired component but allowsany app installed on the device to respond to the intent as long as it satisfies the meta$dataspecifications for the action thats specified in various Intent parameters =or moreinformation see the class about Interacting with ther Apps

Note he reference to 4isplayMessageActivity will raise an error if yoursquore using an I48 suchas 8clipse because the class doesnrsquot exist yet Ignore the error for now7 yoursquoll create the classsoon

An intent not only allows you to start another activity but it can carry a bundle of data to theactivity as well Inside the sendMessage() method use find2iewyId() to get the 8ditext element and add its text value to the intentamp

Intent intent + new Intent(this 4isplayMessageActivityclass)78ditext editext + (8ditext) find2iewyId(gtideditmessage)7tring message + editextgetext()totring()7intentput8xtra(8gtAM8A8 message)7

Note ltou now need import statements for androidcontentIntent andandroidwidget8ditext ltoull define the 8gtAM8A8 constant in a moment

An Intent can carry a collection of various data types as ey$value pairs called extras heput8xtra() method taes the ey name in the first parameter and the value in the secondparameter

In order for the next activity to 6uery the extra data you should define the ey for your intentsextra using a public constant o add the 8gtAM8A8 definition to the top of theMainActivity classamp

public class MainActivity extends Activity 3 public final static tring 8gtAM8A8 + comexamplemyfirstappM8A87 5

Its generally a good practice to define eys for intent extras using your apps pacage nameas a prefix his ensures they are uni6ue in case your app interacts with other apps

Start the Second Activity

o start an activity call startActivity() and pass it your Intent he system receives this call andstarts an instance of the Activity specified by the Intent

ith this new code the complete sendMessage() method thats invoed by the end button

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1316

now loos lie thisamp

11 alled when the user clics the end button 1public void sendMessage(2iew view) 3 Intent intent + new Intent(this 4isplayMessageActivityclass)7 8ditext editext + (8ditext) find2iewyId(gtideditmessage)7 tring message + editextgetext()totring()7 intentput8xtra(8gtAM8A8 message)7

startActivity(intent)75

ow you need to create the 4isplayMessageActivity class in order for this to wor

Create the Second Activity

Figure 1 he new activity wiBard in 8clipseo create a new activity using 8clipseamp

lic New in the toolbar$ In the window that appears open the Android folder and select Android Activity

lic Net- elect BlanActivity and clic NetC =ill in the activity detailsamp

bull roectamp My=irstApp

bull Activity Na$eamp 4isplayMessageActivity

bull ayout Na$eamp activitydisplaymessage

bull Titleamp My Messagebull ampierarchial arentamp comexamplemyfirstappMainActivity

bull Navigation Typeamp one

lic Finish

If youre using a different I48 or the command line tools create a new file named4isplayMessageActivity0ava in the pro0ects src directory next to the original MainActivity0avafile

pen the 4isplayMessageActivity0ava file If you used 8clipse to create this activityamp

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1416

bull he class already includes an implementation of the re6uired onreate() method

bull heres also an implementation of the onreateptionsMenu() method but you wontneed it for this app so you can remove it

bull heres also an implementation of onptionsItemelected() which handles thebehavior for the action bars Up behavior Deep this one the way it is

ecause the Actionar AEIs are available only on 8ltM (AEI level FF) and higher

you must add a condition around the getActionar() method to chec the current platformversion Additionally you must add the -uppressGint(ewApi) tag to the onreate() method to avoid lint errors

he 4isplayMessageActivity class should now loo lie thisamp

public class 4isplayMessageActivity extends Activity 3 -uppressGint(ewApi) -verride protected void onreate(undle savedInstancetate) 3 superonreate(savedInstancetate)7 setontent2iew(gtlayoutactivitydisplaymessage)7 Mae sure were running on oneycomb or higher to use Actionar AEIs

if (uild28gtI4DI + uild28gtI488ltM) 3 how the Hp button in the action bar getActionar()set4isplayomeAsHp8nabled(true)7 5 5 -verride public boolean onptionsItemelected(MenuItem item) 3 switch (itemgetItemId()) 3 case androidgtidhomeamp avHtilsnavigateHp=romameas(this)7 return true7 5 return superonptionsItemelected(item)7 55

If you used an I48 other than 8clipse update your 4isplayMessageActivity class with theabove code

All subclasses of Activity must implement the onreate() method he system calls this whencreating a new instance of the activity his method is where you must define the activitylayout with the setontent2iew() method and is where you should perform initial setup for theactivity components

Note If you are using an I48 other than 8clipse your pro0ect does not contain theactivitydisplaymessage layout thats re6uested by setontent2iew() hats D because

you will update this method later and wont be using that layout

Add the title string

If you used 8clipse you can sip to the next section because the template provides the titlestring for the new activity

If youre using an I48 other than 8clipse add the new activitys title to the stringsxml fileamp

resources

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1516

string name+titleactivitydisplaymessageMy Messagestringresources

Add it to the $aniest

All activities must be declared in your manifest file AndroidManifestxml using an activity element

hen you use the 8clipse tools to create the activity it creates a default entry If youre usinga different I48 you need to add the manifest entry yourself It should loo lie thisamp

application activity androidampname+comexamplemyfirstapp4isplayMessageActivity androidamplabel+-stringtitleactivitydisplaymessage androidampparentActivityame+comexamplemyfirstappMainActivity meta$data androidampname+androidsupportEAgt8AI2Ilt

androidampvalue+comexamplemyfirstappMainActivity activityapplication

he androidampparentActivityame attribute declares the name of this activitys parent activitywithin the apps logical hierarchy he system uses this value to implement default navigationbehaviors such as Hp navigation on Android CF (AEI level F) and higher ltou can providethe same navigation behaviors for older versions of Android by using the upport Gibrary andadding the meta$data element as shown here

Note ltour Android 4D should already include the latest Android upport Gibrary Itsincluded with the A4 undle but if youre using a different I48 you should have installed it

during the Adding Elatforms and Eacages step hen using the templates in 8clipse theupport Gibrary is automatically added to your app pro0ect (you can see the librarys JAgt filelisted under Android Dependencies) If youre not using 8clipse you need to manually add thelibrary to your pro0ectKfollow the guide for setting up the upport Gibrary then return here

If youre developing with 8clipse you can run the app now but not much happens licingthe end button starts the second activity but it uses a default ello world layout providedby the template ltoull soon update the activity to instead display a custom text view so ifyoure using a different I48 dont worry that the app wont yet compile

Receive the Intent

8very Activity is invoed by an Intent regardless of how the user navigated there ltou can getthe Intent that started your activity by calling getIntent() and retrieve the data contained withinit

In the 4isplayMessageActivity classrsquos onreate() method get the intent and extract themessage delivered by MainActivityamp

Intent intent + getIntent()7tring message + intentgettring8xtra(MainActivity8gtAM8A8)7

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1616

(isplay the )essage

o show the message on the screen create a ext2iew widget and set the text usingsetext() hen add the ext2iew as the root view of the activityrsquos layout by passing it tosetontent2iew()

he complete onreate() method for 4isplayMessageActivity now loos lie thisamp

-verridepublic void onreate(undle savedInstancetate) 3 superonreate(savedInstancetate)7 et the message from the intent Intent intent + getIntent()7 tring message + intentgettring8xtra(MainActivity8gtAM8A8)7 reate the text view ext2iew text2iew + new ext2iew(this)7 text2iewsetextiBe(CL)7 text2iewsetext(message)7 et the text view as the activity layout setontent2iew(text2iew)7

5

ltou can now run the app hen it opens type a message in the text field clic end and themessage appears on the second activity

Figure oth activities in the final app running on Android CL

Page 7: 01 Building Your First App

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 716

directly with the 18 so click the activity_mainxml ta at the ottom of the screen to open the 18

editor

The 9lankActiity template you chose when you created this project includes the

activitymainxml file with a 0elative1ayo$t root iew and a extiew child iew

irst delete the ltextiewgt element and change the lt0elative1ayo$tgt element to

lt1inear1ayo$tgt Then add the androidorientation attriute and set it to

)hori2ontal) The result looks like this

lt3xml version()+4) encoding()$t-)3gtlt1inear1ayo$t xmlnsandroid()httpschemasandroidcomapkresandroid) xmlnstools()httpschemasandroidcomtools) androidlayo$twidth()matchparent) androidlayo$theight()matchparent) androidorientation()hori2ontal) gtlt1inear1ayo$tgt

1inear1ayo$t is a iew group (a suclass of iewro$p) that lays out child iews in either a

ertical or horiontal orientation as specified y the androidorientation attriute Each child

of a 1inear1ayo$t appears on the screen in the order in which it appears in the 18The other two attriutes androidlayo$twidth and androidlayo$theight are

re3uired for all iews in order to specify their sie

9ecause the 1inear1ayo$t is the root iew in the layout it should fill the entire screen area thats

aailale to the app y setting the width and height to )matchparent) This alue declares that the

iew should e4pand its width or height to match the width or height of the parent iew

or more information aout layout properties see the 8ayout guide

Add a ext Field

To create a usereditale te4t field add an lt5ditextgt element inside the lt1inear1ayo$tgt

8ike eery iew oject you must define certain 18 attriutes to specify the 5ditext ojects

properties 5eres how you should declare it inside the lt1inear1ayo$tgt element

lt5ditext androidid()67ideditmessage) androidlayo$twidth()wrapcontent) androidlayo$theight()wrapcontent) androidhint()6stringeditmessage) gt

A-out resource o-jects

A resource oject is simply a uni3ue integer name thats associated with an app resource such as a itmap layout file or string

Eery resource has a corresponding resource oject defined in your projects gen0java file ou

can use the oject names in the 0 class to refer to your resources such as when you need to specify a

string alue for the androidhint attriute ou can also create aritrary resource Ds that you

associate with a iew using the androidid attriute which allows you to reference that iew from

other code

The SDK tools generate the 0java each time you compile your app ou should neer modify this

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 816

file y hand

or more information read the guide to +roiding Cesources

Aout these attriutes

androidid

This proides a uni3ue identifier for the iew which you can use to reference the oject from

your app code such as to read and manipulate the oject (youll see this in the ne4t lesson)

The at sign (6) is re3uired when youre referring to any resource oject from 18 t is followed

y the resource type (id in this case) a slash then the resource name (editmessage)

The plus sign (7) efore the resource type is needed only when youre defining a resource D for

the first time Bhen you compile the app the SDK tools use the D name to create a new

resource D in your projects gen0java file that refers to the 5ditext element =nce the

resource D is declared once this way other references to the D do not need the plus sign ltsing

the plus sign is necessary only when specifying a new resource D and not needed for concreteresources such as strings or layouts See the sideo4 for more information aout resource ojects

androidlayo$twidth and androidlayo$theight

nstead of using specific sies for the width and height the )wrapcontent) alue specifies

that the iew should e only as ig as needed to fit the contents of the iew f you were to

instead use )matchparent) then the 5ditext element would fill the screen ecause it

would match the sie of the parent 1inear1ayo$t or more information see the 8ayouts

guideandroidhint

This is a default string to display when the te4t field is empty nstead of using a hardcoded

string as the alue the )6stringeditmessage) alue refers to a string resource defined

in a separate file 9ecause this refers to a concrete resource (not just an identifier) it does not

need the plus sign 5oweer ecause you haent defined the string resource yet youll see acompiler error at first oull fi4 this in the ne4t section y defining the string

Note This string resource has the same name as the element D editmessage 5oweer

references to resources are always scoped y the resource type (such as id or string) so using

the same name does not cause collisions

Add tring esources

Bhen you need to add te4t in the user interface you should always specify each string as a resource

String resources allow you to manage all lt te4t in a single location which makes it easier to find and

update te4t E4ternaliing the strings also allows you to localie your app to different languages y proiding alternatie definitions for each string resource

9y default your Android project includes a string resource file at resval$esstringsxml

Add a new string named )editmessage) and set the alue to 0Enter a message0 (ou can delete

the 0helloGworld0 string)

Bhile youre in this file also add a 0Send0 string for the utton youll soon add called

)$ttonsend)

The result for stringsxml looks like this

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 916

lt3xml version()+4) encoding()$t-)3gtltreso$rcesgt ltstring name()appname)gtMy First Appltstringgt ltstring name()editmessage)gt5nter a messageltstringgt ltstring name()$ttonsend)gtampendltstringgt ltstring name()actionsettings)gtampettingsltstringgt ltstring name()titleactivitymain)gtMainActivityltstringgtltreso$rcesgt

or more information aout using string resources to localie your app for other languages see the

Supporting Different Deices class

Add a utton

ow add a lt8$ttongt to the layout immediately following the lt5ditextgt element

lt8$tton androidlayo$twidth()wrapcontent) androidlayo$theight()wrapcontent) androidtext()6string$ttonsend) gt

The height and width are set to )wrapcontent) so the utton is only as ig as necessary to fit the

uttons te4t This utton doesnt need the androidid attriute ecause it wont e referenced from

the actiity code

Make the nput ox Fill in the creen ampidth

The layout is currently designed so that oth the 5ditext and 8$tton widgets are only as ig as

necessary to fit their content as shown in figure $

Figure 3 The 5ditext and 8$tton widgets hae their widths set to )wrapcontent)

This works fine for the utton ut not as well for the te4t field ecause the user might type somethinglonger So it would e nice to fill the unused screen width with the te4t field ou can do this inside a

1inear1ayo$t with the weight property which you can specify using the

androidlayo$tweight attriute

The weight alue is a numer that specifies the amount of remaining space each iew should consume

relatie to the amount consumed y siling iews This works kind of like the amount of ingredients in

a drink recipe 0$ parts odka part coffee li3ueur0 means twothirds of the drink is odka ore4ample if you gie one iew a weight of $ and another one a weight of the sum is - so the firstiew fills $H- of the remaining space and the second iew fills the rest f you add a third iew and gie

it a weight of then the first iew (with weight of $) now gets H$ the remaining space while the

remaining two each get H

The default weight for all iews is amp so if you specify any weight alue greater than amp to only oneiew then that iew fills whateer space remains after all iews are gien the space they re3uire So to

fill the remaining space in your layout with the 5ditext element gie it a weight of and leae the

utton with no weight

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1016

lt5ditext androidlayo$tweight()+) gt

n order to improe the layout efficiency when you specify the weight you should change the width of

the 5ditext to e ero (ampdp) Setting the width to ero improes layout performance ecause using

)wrapcontent) as the width re3uires the system to calculate a width that is ultimately irreleant

ecause the weight alue re3uires another width calculation to fill the remaining space

lt5ditext androidlayo$tweight()+) androidlayo$twidth()4dp) gt

igure - shows the result when you assign all weight to the 5ditext element

Figure 4 The 5ditext widget is gien all the layout weight so fills the remaining space in the

1inear1ayo$t

5eres how your complete layout file should now look

lt3xml version()+4) encoding()$t-)3gtlt1inear1ayo$t xmlnsandroid()httpschemasandroidcomapkresandroid) xmlnstools()httpschemasandroidcomtools) androidlayo$twidth()matchparent) androidlayo$theight()matchparent) androidorientation()hori2ontal)gt lt5ditext androidid()67ideditmessage) androidlayo$tweight()+)

androidlayo$twidth()4dp) androidlayo$theight()wrapcontent) androidhint()6stringeditmessage) gt lt8$tton androidlayo$twidth()wrapcontent) androidlayo$theight()wrapcontent) androidtext()6string$ttonsend) gtlt1inear1ayo$tgt

This layout is applied y the default Activity class that the SDK tools generated when you created

the project so you can now run the app to see the results

bull n Eclipse click Cun from the toolar

bull =r from a command line change directories to the root of your Android project and e4ecute

ant de$gad install inMyFirstApp-de$gapk

ontinue to the ne4t lesson to learn how you can respond to utton presses read content from the te4t

field start another actiity and more

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1116

tarting Another Acti(it)

After completing the previous lesson you have an app that shows an activity (a single screen)with a text field and a button In this lesson yoursquoll add some code to MainActivity that starts anew activity when the user clics the end button

Respond to the Send Button

o respond to the buttons on$clic event open the activitymainxml layout file and add theandroidamponlic attribute to the utton elementamp

utton androidamplayoutwidth+wrapcontent androidamplayoutheight+wrapcontent androidamptext+-stringbuttonsend androidamponlic+sendMessage

he androidamponlic attributersquos value sendMessage is the name of a method in youractivity that the system calls when the user clics the button

pen the MainActivity class (located in the pro0ects src directory) and add the correspondingmethodamp

11 alled when the user clics the end button 1public void sendMessage(2iew view) 3 4o something in response to button5

his re6uires that you import the 2iew classamp

import androidview2iew7

Tip In 8clipse press trl 9 hift 9 to import missing classes (md 9 hift 9 on Mac)

In order for the system to match this method to the method name given to androidamponlicthe signature must be exactly as shown pecifically the method mustamp

bull e public

bull ave a void return value

bull ave a 2iew as the only parameter (this will be the 2iew that was cliced)

ext yoursquoll fill in this method to read the contents of the text field and deliver that text toanother activity

Build an Intent

An Intent is an ob0ect that provides runtime binding between separate components (such astwo activities) he Intent represents an apprsquos intent to do something ltou can use intentsfor a wide variety of tass but most often theyrsquore used to start another activity

Inside the sendMessage() method create an Intent to start an activity called4isplayMessageActivityamp

Intent intent + new Intent(this 4isplayMessageActivityclass)7

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1216

he constructor used here taes two parametersamp

bull A ontext as its first parameter (this is used because the Activity class is a subclass ofontext)

bull he lass of the app component to which the system should deliver the Intent (in thiscase the activity that should be started)

Sending an intent to other apps

he intent created in this lesson is whats considered an explicit intent because the Intent specifies the exact app component to which the intent should be given owever intents canalso be implicit in which case the Intent does not specify the desired component but allowsany app installed on the device to respond to the intent as long as it satisfies the meta$dataspecifications for the action thats specified in various Intent parameters =or moreinformation see the class about Interacting with ther Apps

Note he reference to 4isplayMessageActivity will raise an error if yoursquore using an I48 suchas 8clipse because the class doesnrsquot exist yet Ignore the error for now7 yoursquoll create the classsoon

An intent not only allows you to start another activity but it can carry a bundle of data to theactivity as well Inside the sendMessage() method use find2iewyId() to get the 8ditext element and add its text value to the intentamp

Intent intent + new Intent(this 4isplayMessageActivityclass)78ditext editext + (8ditext) find2iewyId(gtideditmessage)7tring message + editextgetext()totring()7intentput8xtra(8gtAM8A8 message)7

Note ltou now need import statements for androidcontentIntent andandroidwidget8ditext ltoull define the 8gtAM8A8 constant in a moment

An Intent can carry a collection of various data types as ey$value pairs called extras heput8xtra() method taes the ey name in the first parameter and the value in the secondparameter

In order for the next activity to 6uery the extra data you should define the ey for your intentsextra using a public constant o add the 8gtAM8A8 definition to the top of theMainActivity classamp

public class MainActivity extends Activity 3 public final static tring 8gtAM8A8 + comexamplemyfirstappM8A87 5

Its generally a good practice to define eys for intent extras using your apps pacage nameas a prefix his ensures they are uni6ue in case your app interacts with other apps

Start the Second Activity

o start an activity call startActivity() and pass it your Intent he system receives this call andstarts an instance of the Activity specified by the Intent

ith this new code the complete sendMessage() method thats invoed by the end button

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1316

now loos lie thisamp

11 alled when the user clics the end button 1public void sendMessage(2iew view) 3 Intent intent + new Intent(this 4isplayMessageActivityclass)7 8ditext editext + (8ditext) find2iewyId(gtideditmessage)7 tring message + editextgetext()totring()7 intentput8xtra(8gtAM8A8 message)7

startActivity(intent)75

ow you need to create the 4isplayMessageActivity class in order for this to wor

Create the Second Activity

Figure 1 he new activity wiBard in 8clipseo create a new activity using 8clipseamp

lic New in the toolbar$ In the window that appears open the Android folder and select Android Activity

lic Net- elect BlanActivity and clic NetC =ill in the activity detailsamp

bull roectamp My=irstApp

bull Activity Na$eamp 4isplayMessageActivity

bull ayout Na$eamp activitydisplaymessage

bull Titleamp My Messagebull ampierarchial arentamp comexamplemyfirstappMainActivity

bull Navigation Typeamp one

lic Finish

If youre using a different I48 or the command line tools create a new file named4isplayMessageActivity0ava in the pro0ects src directory next to the original MainActivity0avafile

pen the 4isplayMessageActivity0ava file If you used 8clipse to create this activityamp

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1416

bull he class already includes an implementation of the re6uired onreate() method

bull heres also an implementation of the onreateptionsMenu() method but you wontneed it for this app so you can remove it

bull heres also an implementation of onptionsItemelected() which handles thebehavior for the action bars Up behavior Deep this one the way it is

ecause the Actionar AEIs are available only on 8ltM (AEI level FF) and higher

you must add a condition around the getActionar() method to chec the current platformversion Additionally you must add the -uppressGint(ewApi) tag to the onreate() method to avoid lint errors

he 4isplayMessageActivity class should now loo lie thisamp

public class 4isplayMessageActivity extends Activity 3 -uppressGint(ewApi) -verride protected void onreate(undle savedInstancetate) 3 superonreate(savedInstancetate)7 setontent2iew(gtlayoutactivitydisplaymessage)7 Mae sure were running on oneycomb or higher to use Actionar AEIs

if (uild28gtI4DI + uild28gtI488ltM) 3 how the Hp button in the action bar getActionar()set4isplayomeAsHp8nabled(true)7 5 5 -verride public boolean onptionsItemelected(MenuItem item) 3 switch (itemgetItemId()) 3 case androidgtidhomeamp avHtilsnavigateHp=romameas(this)7 return true7 5 return superonptionsItemelected(item)7 55

If you used an I48 other than 8clipse update your 4isplayMessageActivity class with theabove code

All subclasses of Activity must implement the onreate() method he system calls this whencreating a new instance of the activity his method is where you must define the activitylayout with the setontent2iew() method and is where you should perform initial setup for theactivity components

Note If you are using an I48 other than 8clipse your pro0ect does not contain theactivitydisplaymessage layout thats re6uested by setontent2iew() hats D because

you will update this method later and wont be using that layout

Add the title string

If you used 8clipse you can sip to the next section because the template provides the titlestring for the new activity

If youre using an I48 other than 8clipse add the new activitys title to the stringsxml fileamp

resources

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1516

string name+titleactivitydisplaymessageMy Messagestringresources

Add it to the $aniest

All activities must be declared in your manifest file AndroidManifestxml using an activity element

hen you use the 8clipse tools to create the activity it creates a default entry If youre usinga different I48 you need to add the manifest entry yourself It should loo lie thisamp

application activity androidampname+comexamplemyfirstapp4isplayMessageActivity androidamplabel+-stringtitleactivitydisplaymessage androidampparentActivityame+comexamplemyfirstappMainActivity meta$data androidampname+androidsupportEAgt8AI2Ilt

androidampvalue+comexamplemyfirstappMainActivity activityapplication

he androidampparentActivityame attribute declares the name of this activitys parent activitywithin the apps logical hierarchy he system uses this value to implement default navigationbehaviors such as Hp navigation on Android CF (AEI level F) and higher ltou can providethe same navigation behaviors for older versions of Android by using the upport Gibrary andadding the meta$data element as shown here

Note ltour Android 4D should already include the latest Android upport Gibrary Itsincluded with the A4 undle but if youre using a different I48 you should have installed it

during the Adding Elatforms and Eacages step hen using the templates in 8clipse theupport Gibrary is automatically added to your app pro0ect (you can see the librarys JAgt filelisted under Android Dependencies) If youre not using 8clipse you need to manually add thelibrary to your pro0ectKfollow the guide for setting up the upport Gibrary then return here

If youre developing with 8clipse you can run the app now but not much happens licingthe end button starts the second activity but it uses a default ello world layout providedby the template ltoull soon update the activity to instead display a custom text view so ifyoure using a different I48 dont worry that the app wont yet compile

Receive the Intent

8very Activity is invoed by an Intent regardless of how the user navigated there ltou can getthe Intent that started your activity by calling getIntent() and retrieve the data contained withinit

In the 4isplayMessageActivity classrsquos onreate() method get the intent and extract themessage delivered by MainActivityamp

Intent intent + getIntent()7tring message + intentgettring8xtra(MainActivity8gtAM8A8)7

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1616

(isplay the )essage

o show the message on the screen create a ext2iew widget and set the text usingsetext() hen add the ext2iew as the root view of the activityrsquos layout by passing it tosetontent2iew()

he complete onreate() method for 4isplayMessageActivity now loos lie thisamp

-verridepublic void onreate(undle savedInstancetate) 3 superonreate(savedInstancetate)7 et the message from the intent Intent intent + getIntent()7 tring message + intentgettring8xtra(MainActivity8gtAM8A8)7 reate the text view ext2iew text2iew + new ext2iew(this)7 text2iewsetextiBe(CL)7 text2iewsetext(message)7 et the text view as the activity layout setontent2iew(text2iew)7

5

ltou can now run the app hen it opens type a message in the text field clic end and themessage appears on the second activity

Figure oth activities in the final app running on Android CL

Page 8: 01 Building Your First App

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 816

file y hand

or more information read the guide to +roiding Cesources

Aout these attriutes

androidid

This proides a uni3ue identifier for the iew which you can use to reference the oject from

your app code such as to read and manipulate the oject (youll see this in the ne4t lesson)

The at sign (6) is re3uired when youre referring to any resource oject from 18 t is followed

y the resource type (id in this case) a slash then the resource name (editmessage)

The plus sign (7) efore the resource type is needed only when youre defining a resource D for

the first time Bhen you compile the app the SDK tools use the D name to create a new

resource D in your projects gen0java file that refers to the 5ditext element =nce the

resource D is declared once this way other references to the D do not need the plus sign ltsing

the plus sign is necessary only when specifying a new resource D and not needed for concreteresources such as strings or layouts See the sideo4 for more information aout resource ojects

androidlayo$twidth and androidlayo$theight

nstead of using specific sies for the width and height the )wrapcontent) alue specifies

that the iew should e only as ig as needed to fit the contents of the iew f you were to

instead use )matchparent) then the 5ditext element would fill the screen ecause it

would match the sie of the parent 1inear1ayo$t or more information see the 8ayouts

guideandroidhint

This is a default string to display when the te4t field is empty nstead of using a hardcoded

string as the alue the )6stringeditmessage) alue refers to a string resource defined

in a separate file 9ecause this refers to a concrete resource (not just an identifier) it does not

need the plus sign 5oweer ecause you haent defined the string resource yet youll see acompiler error at first oull fi4 this in the ne4t section y defining the string

Note This string resource has the same name as the element D editmessage 5oweer

references to resources are always scoped y the resource type (such as id or string) so using

the same name does not cause collisions

Add tring esources

Bhen you need to add te4t in the user interface you should always specify each string as a resource

String resources allow you to manage all lt te4t in a single location which makes it easier to find and

update te4t E4ternaliing the strings also allows you to localie your app to different languages y proiding alternatie definitions for each string resource

9y default your Android project includes a string resource file at resval$esstringsxml

Add a new string named )editmessage) and set the alue to 0Enter a message0 (ou can delete

the 0helloGworld0 string)

Bhile youre in this file also add a 0Send0 string for the utton youll soon add called

)$ttonsend)

The result for stringsxml looks like this

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 916

lt3xml version()+4) encoding()$t-)3gtltreso$rcesgt ltstring name()appname)gtMy First Appltstringgt ltstring name()editmessage)gt5nter a messageltstringgt ltstring name()$ttonsend)gtampendltstringgt ltstring name()actionsettings)gtampettingsltstringgt ltstring name()titleactivitymain)gtMainActivityltstringgtltreso$rcesgt

or more information aout using string resources to localie your app for other languages see the

Supporting Different Deices class

Add a utton

ow add a lt8$ttongt to the layout immediately following the lt5ditextgt element

lt8$tton androidlayo$twidth()wrapcontent) androidlayo$theight()wrapcontent) androidtext()6string$ttonsend) gt

The height and width are set to )wrapcontent) so the utton is only as ig as necessary to fit the

uttons te4t This utton doesnt need the androidid attriute ecause it wont e referenced from

the actiity code

Make the nput ox Fill in the creen ampidth

The layout is currently designed so that oth the 5ditext and 8$tton widgets are only as ig as

necessary to fit their content as shown in figure $

Figure 3 The 5ditext and 8$tton widgets hae their widths set to )wrapcontent)

This works fine for the utton ut not as well for the te4t field ecause the user might type somethinglonger So it would e nice to fill the unused screen width with the te4t field ou can do this inside a

1inear1ayo$t with the weight property which you can specify using the

androidlayo$tweight attriute

The weight alue is a numer that specifies the amount of remaining space each iew should consume

relatie to the amount consumed y siling iews This works kind of like the amount of ingredients in

a drink recipe 0$ parts odka part coffee li3ueur0 means twothirds of the drink is odka ore4ample if you gie one iew a weight of $ and another one a weight of the sum is - so the firstiew fills $H- of the remaining space and the second iew fills the rest f you add a third iew and gie

it a weight of then the first iew (with weight of $) now gets H$ the remaining space while the

remaining two each get H

The default weight for all iews is amp so if you specify any weight alue greater than amp to only oneiew then that iew fills whateer space remains after all iews are gien the space they re3uire So to

fill the remaining space in your layout with the 5ditext element gie it a weight of and leae the

utton with no weight

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1016

lt5ditext androidlayo$tweight()+) gt

n order to improe the layout efficiency when you specify the weight you should change the width of

the 5ditext to e ero (ampdp) Setting the width to ero improes layout performance ecause using

)wrapcontent) as the width re3uires the system to calculate a width that is ultimately irreleant

ecause the weight alue re3uires another width calculation to fill the remaining space

lt5ditext androidlayo$tweight()+) androidlayo$twidth()4dp) gt

igure - shows the result when you assign all weight to the 5ditext element

Figure 4 The 5ditext widget is gien all the layout weight so fills the remaining space in the

1inear1ayo$t

5eres how your complete layout file should now look

lt3xml version()+4) encoding()$t-)3gtlt1inear1ayo$t xmlnsandroid()httpschemasandroidcomapkresandroid) xmlnstools()httpschemasandroidcomtools) androidlayo$twidth()matchparent) androidlayo$theight()matchparent) androidorientation()hori2ontal)gt lt5ditext androidid()67ideditmessage) androidlayo$tweight()+)

androidlayo$twidth()4dp) androidlayo$theight()wrapcontent) androidhint()6stringeditmessage) gt lt8$tton androidlayo$twidth()wrapcontent) androidlayo$theight()wrapcontent) androidtext()6string$ttonsend) gtlt1inear1ayo$tgt

This layout is applied y the default Activity class that the SDK tools generated when you created

the project so you can now run the app to see the results

bull n Eclipse click Cun from the toolar

bull =r from a command line change directories to the root of your Android project and e4ecute

ant de$gad install inMyFirstApp-de$gapk

ontinue to the ne4t lesson to learn how you can respond to utton presses read content from the te4t

field start another actiity and more

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1116

tarting Another Acti(it)

After completing the previous lesson you have an app that shows an activity (a single screen)with a text field and a button In this lesson yoursquoll add some code to MainActivity that starts anew activity when the user clics the end button

Respond to the Send Button

o respond to the buttons on$clic event open the activitymainxml layout file and add theandroidamponlic attribute to the utton elementamp

utton androidamplayoutwidth+wrapcontent androidamplayoutheight+wrapcontent androidamptext+-stringbuttonsend androidamponlic+sendMessage

he androidamponlic attributersquos value sendMessage is the name of a method in youractivity that the system calls when the user clics the button

pen the MainActivity class (located in the pro0ects src directory) and add the correspondingmethodamp

11 alled when the user clics the end button 1public void sendMessage(2iew view) 3 4o something in response to button5

his re6uires that you import the 2iew classamp

import androidview2iew7

Tip In 8clipse press trl 9 hift 9 to import missing classes (md 9 hift 9 on Mac)

In order for the system to match this method to the method name given to androidamponlicthe signature must be exactly as shown pecifically the method mustamp

bull e public

bull ave a void return value

bull ave a 2iew as the only parameter (this will be the 2iew that was cliced)

ext yoursquoll fill in this method to read the contents of the text field and deliver that text toanother activity

Build an Intent

An Intent is an ob0ect that provides runtime binding between separate components (such astwo activities) he Intent represents an apprsquos intent to do something ltou can use intentsfor a wide variety of tass but most often theyrsquore used to start another activity

Inside the sendMessage() method create an Intent to start an activity called4isplayMessageActivityamp

Intent intent + new Intent(this 4isplayMessageActivityclass)7

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1216

he constructor used here taes two parametersamp

bull A ontext as its first parameter (this is used because the Activity class is a subclass ofontext)

bull he lass of the app component to which the system should deliver the Intent (in thiscase the activity that should be started)

Sending an intent to other apps

he intent created in this lesson is whats considered an explicit intent because the Intent specifies the exact app component to which the intent should be given owever intents canalso be implicit in which case the Intent does not specify the desired component but allowsany app installed on the device to respond to the intent as long as it satisfies the meta$dataspecifications for the action thats specified in various Intent parameters =or moreinformation see the class about Interacting with ther Apps

Note he reference to 4isplayMessageActivity will raise an error if yoursquore using an I48 suchas 8clipse because the class doesnrsquot exist yet Ignore the error for now7 yoursquoll create the classsoon

An intent not only allows you to start another activity but it can carry a bundle of data to theactivity as well Inside the sendMessage() method use find2iewyId() to get the 8ditext element and add its text value to the intentamp

Intent intent + new Intent(this 4isplayMessageActivityclass)78ditext editext + (8ditext) find2iewyId(gtideditmessage)7tring message + editextgetext()totring()7intentput8xtra(8gtAM8A8 message)7

Note ltou now need import statements for androidcontentIntent andandroidwidget8ditext ltoull define the 8gtAM8A8 constant in a moment

An Intent can carry a collection of various data types as ey$value pairs called extras heput8xtra() method taes the ey name in the first parameter and the value in the secondparameter

In order for the next activity to 6uery the extra data you should define the ey for your intentsextra using a public constant o add the 8gtAM8A8 definition to the top of theMainActivity classamp

public class MainActivity extends Activity 3 public final static tring 8gtAM8A8 + comexamplemyfirstappM8A87 5

Its generally a good practice to define eys for intent extras using your apps pacage nameas a prefix his ensures they are uni6ue in case your app interacts with other apps

Start the Second Activity

o start an activity call startActivity() and pass it your Intent he system receives this call andstarts an instance of the Activity specified by the Intent

ith this new code the complete sendMessage() method thats invoed by the end button

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1316

now loos lie thisamp

11 alled when the user clics the end button 1public void sendMessage(2iew view) 3 Intent intent + new Intent(this 4isplayMessageActivityclass)7 8ditext editext + (8ditext) find2iewyId(gtideditmessage)7 tring message + editextgetext()totring()7 intentput8xtra(8gtAM8A8 message)7

startActivity(intent)75

ow you need to create the 4isplayMessageActivity class in order for this to wor

Create the Second Activity

Figure 1 he new activity wiBard in 8clipseo create a new activity using 8clipseamp

lic New in the toolbar$ In the window that appears open the Android folder and select Android Activity

lic Net- elect BlanActivity and clic NetC =ill in the activity detailsamp

bull roectamp My=irstApp

bull Activity Na$eamp 4isplayMessageActivity

bull ayout Na$eamp activitydisplaymessage

bull Titleamp My Messagebull ampierarchial arentamp comexamplemyfirstappMainActivity

bull Navigation Typeamp one

lic Finish

If youre using a different I48 or the command line tools create a new file named4isplayMessageActivity0ava in the pro0ects src directory next to the original MainActivity0avafile

pen the 4isplayMessageActivity0ava file If you used 8clipse to create this activityamp

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1416

bull he class already includes an implementation of the re6uired onreate() method

bull heres also an implementation of the onreateptionsMenu() method but you wontneed it for this app so you can remove it

bull heres also an implementation of onptionsItemelected() which handles thebehavior for the action bars Up behavior Deep this one the way it is

ecause the Actionar AEIs are available only on 8ltM (AEI level FF) and higher

you must add a condition around the getActionar() method to chec the current platformversion Additionally you must add the -uppressGint(ewApi) tag to the onreate() method to avoid lint errors

he 4isplayMessageActivity class should now loo lie thisamp

public class 4isplayMessageActivity extends Activity 3 -uppressGint(ewApi) -verride protected void onreate(undle savedInstancetate) 3 superonreate(savedInstancetate)7 setontent2iew(gtlayoutactivitydisplaymessage)7 Mae sure were running on oneycomb or higher to use Actionar AEIs

if (uild28gtI4DI + uild28gtI488ltM) 3 how the Hp button in the action bar getActionar()set4isplayomeAsHp8nabled(true)7 5 5 -verride public boolean onptionsItemelected(MenuItem item) 3 switch (itemgetItemId()) 3 case androidgtidhomeamp avHtilsnavigateHp=romameas(this)7 return true7 5 return superonptionsItemelected(item)7 55

If you used an I48 other than 8clipse update your 4isplayMessageActivity class with theabove code

All subclasses of Activity must implement the onreate() method he system calls this whencreating a new instance of the activity his method is where you must define the activitylayout with the setontent2iew() method and is where you should perform initial setup for theactivity components

Note If you are using an I48 other than 8clipse your pro0ect does not contain theactivitydisplaymessage layout thats re6uested by setontent2iew() hats D because

you will update this method later and wont be using that layout

Add the title string

If you used 8clipse you can sip to the next section because the template provides the titlestring for the new activity

If youre using an I48 other than 8clipse add the new activitys title to the stringsxml fileamp

resources

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1516

string name+titleactivitydisplaymessageMy Messagestringresources

Add it to the $aniest

All activities must be declared in your manifest file AndroidManifestxml using an activity element

hen you use the 8clipse tools to create the activity it creates a default entry If youre usinga different I48 you need to add the manifest entry yourself It should loo lie thisamp

application activity androidampname+comexamplemyfirstapp4isplayMessageActivity androidamplabel+-stringtitleactivitydisplaymessage androidampparentActivityame+comexamplemyfirstappMainActivity meta$data androidampname+androidsupportEAgt8AI2Ilt

androidampvalue+comexamplemyfirstappMainActivity activityapplication

he androidampparentActivityame attribute declares the name of this activitys parent activitywithin the apps logical hierarchy he system uses this value to implement default navigationbehaviors such as Hp navigation on Android CF (AEI level F) and higher ltou can providethe same navigation behaviors for older versions of Android by using the upport Gibrary andadding the meta$data element as shown here

Note ltour Android 4D should already include the latest Android upport Gibrary Itsincluded with the A4 undle but if youre using a different I48 you should have installed it

during the Adding Elatforms and Eacages step hen using the templates in 8clipse theupport Gibrary is automatically added to your app pro0ect (you can see the librarys JAgt filelisted under Android Dependencies) If youre not using 8clipse you need to manually add thelibrary to your pro0ectKfollow the guide for setting up the upport Gibrary then return here

If youre developing with 8clipse you can run the app now but not much happens licingthe end button starts the second activity but it uses a default ello world layout providedby the template ltoull soon update the activity to instead display a custom text view so ifyoure using a different I48 dont worry that the app wont yet compile

Receive the Intent

8very Activity is invoed by an Intent regardless of how the user navigated there ltou can getthe Intent that started your activity by calling getIntent() and retrieve the data contained withinit

In the 4isplayMessageActivity classrsquos onreate() method get the intent and extract themessage delivered by MainActivityamp

Intent intent + getIntent()7tring message + intentgettring8xtra(MainActivity8gtAM8A8)7

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1616

(isplay the )essage

o show the message on the screen create a ext2iew widget and set the text usingsetext() hen add the ext2iew as the root view of the activityrsquos layout by passing it tosetontent2iew()

he complete onreate() method for 4isplayMessageActivity now loos lie thisamp

-verridepublic void onreate(undle savedInstancetate) 3 superonreate(savedInstancetate)7 et the message from the intent Intent intent + getIntent()7 tring message + intentgettring8xtra(MainActivity8gtAM8A8)7 reate the text view ext2iew text2iew + new ext2iew(this)7 text2iewsetextiBe(CL)7 text2iewsetext(message)7 et the text view as the activity layout setontent2iew(text2iew)7

5

ltou can now run the app hen it opens type a message in the text field clic end and themessage appears on the second activity

Figure oth activities in the final app running on Android CL

Page 9: 01 Building Your First App

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 916

lt3xml version()+4) encoding()$t-)3gtltreso$rcesgt ltstring name()appname)gtMy First Appltstringgt ltstring name()editmessage)gt5nter a messageltstringgt ltstring name()$ttonsend)gtampendltstringgt ltstring name()actionsettings)gtampettingsltstringgt ltstring name()titleactivitymain)gtMainActivityltstringgtltreso$rcesgt

or more information aout using string resources to localie your app for other languages see the

Supporting Different Deices class

Add a utton

ow add a lt8$ttongt to the layout immediately following the lt5ditextgt element

lt8$tton androidlayo$twidth()wrapcontent) androidlayo$theight()wrapcontent) androidtext()6string$ttonsend) gt

The height and width are set to )wrapcontent) so the utton is only as ig as necessary to fit the

uttons te4t This utton doesnt need the androidid attriute ecause it wont e referenced from

the actiity code

Make the nput ox Fill in the creen ampidth

The layout is currently designed so that oth the 5ditext and 8$tton widgets are only as ig as

necessary to fit their content as shown in figure $

Figure 3 The 5ditext and 8$tton widgets hae their widths set to )wrapcontent)

This works fine for the utton ut not as well for the te4t field ecause the user might type somethinglonger So it would e nice to fill the unused screen width with the te4t field ou can do this inside a

1inear1ayo$t with the weight property which you can specify using the

androidlayo$tweight attriute

The weight alue is a numer that specifies the amount of remaining space each iew should consume

relatie to the amount consumed y siling iews This works kind of like the amount of ingredients in

a drink recipe 0$ parts odka part coffee li3ueur0 means twothirds of the drink is odka ore4ample if you gie one iew a weight of $ and another one a weight of the sum is - so the firstiew fills $H- of the remaining space and the second iew fills the rest f you add a third iew and gie

it a weight of then the first iew (with weight of $) now gets H$ the remaining space while the

remaining two each get H

The default weight for all iews is amp so if you specify any weight alue greater than amp to only oneiew then that iew fills whateer space remains after all iews are gien the space they re3uire So to

fill the remaining space in your layout with the 5ditext element gie it a weight of and leae the

utton with no weight

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1016

lt5ditext androidlayo$tweight()+) gt

n order to improe the layout efficiency when you specify the weight you should change the width of

the 5ditext to e ero (ampdp) Setting the width to ero improes layout performance ecause using

)wrapcontent) as the width re3uires the system to calculate a width that is ultimately irreleant

ecause the weight alue re3uires another width calculation to fill the remaining space

lt5ditext androidlayo$tweight()+) androidlayo$twidth()4dp) gt

igure - shows the result when you assign all weight to the 5ditext element

Figure 4 The 5ditext widget is gien all the layout weight so fills the remaining space in the

1inear1ayo$t

5eres how your complete layout file should now look

lt3xml version()+4) encoding()$t-)3gtlt1inear1ayo$t xmlnsandroid()httpschemasandroidcomapkresandroid) xmlnstools()httpschemasandroidcomtools) androidlayo$twidth()matchparent) androidlayo$theight()matchparent) androidorientation()hori2ontal)gt lt5ditext androidid()67ideditmessage) androidlayo$tweight()+)

androidlayo$twidth()4dp) androidlayo$theight()wrapcontent) androidhint()6stringeditmessage) gt lt8$tton androidlayo$twidth()wrapcontent) androidlayo$theight()wrapcontent) androidtext()6string$ttonsend) gtlt1inear1ayo$tgt

This layout is applied y the default Activity class that the SDK tools generated when you created

the project so you can now run the app to see the results

bull n Eclipse click Cun from the toolar

bull =r from a command line change directories to the root of your Android project and e4ecute

ant de$gad install inMyFirstApp-de$gapk

ontinue to the ne4t lesson to learn how you can respond to utton presses read content from the te4t

field start another actiity and more

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1116

tarting Another Acti(it)

After completing the previous lesson you have an app that shows an activity (a single screen)with a text field and a button In this lesson yoursquoll add some code to MainActivity that starts anew activity when the user clics the end button

Respond to the Send Button

o respond to the buttons on$clic event open the activitymainxml layout file and add theandroidamponlic attribute to the utton elementamp

utton androidamplayoutwidth+wrapcontent androidamplayoutheight+wrapcontent androidamptext+-stringbuttonsend androidamponlic+sendMessage

he androidamponlic attributersquos value sendMessage is the name of a method in youractivity that the system calls when the user clics the button

pen the MainActivity class (located in the pro0ects src directory) and add the correspondingmethodamp

11 alled when the user clics the end button 1public void sendMessage(2iew view) 3 4o something in response to button5

his re6uires that you import the 2iew classamp

import androidview2iew7

Tip In 8clipse press trl 9 hift 9 to import missing classes (md 9 hift 9 on Mac)

In order for the system to match this method to the method name given to androidamponlicthe signature must be exactly as shown pecifically the method mustamp

bull e public

bull ave a void return value

bull ave a 2iew as the only parameter (this will be the 2iew that was cliced)

ext yoursquoll fill in this method to read the contents of the text field and deliver that text toanother activity

Build an Intent

An Intent is an ob0ect that provides runtime binding between separate components (such astwo activities) he Intent represents an apprsquos intent to do something ltou can use intentsfor a wide variety of tass but most often theyrsquore used to start another activity

Inside the sendMessage() method create an Intent to start an activity called4isplayMessageActivityamp

Intent intent + new Intent(this 4isplayMessageActivityclass)7

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1216

he constructor used here taes two parametersamp

bull A ontext as its first parameter (this is used because the Activity class is a subclass ofontext)

bull he lass of the app component to which the system should deliver the Intent (in thiscase the activity that should be started)

Sending an intent to other apps

he intent created in this lesson is whats considered an explicit intent because the Intent specifies the exact app component to which the intent should be given owever intents canalso be implicit in which case the Intent does not specify the desired component but allowsany app installed on the device to respond to the intent as long as it satisfies the meta$dataspecifications for the action thats specified in various Intent parameters =or moreinformation see the class about Interacting with ther Apps

Note he reference to 4isplayMessageActivity will raise an error if yoursquore using an I48 suchas 8clipse because the class doesnrsquot exist yet Ignore the error for now7 yoursquoll create the classsoon

An intent not only allows you to start another activity but it can carry a bundle of data to theactivity as well Inside the sendMessage() method use find2iewyId() to get the 8ditext element and add its text value to the intentamp

Intent intent + new Intent(this 4isplayMessageActivityclass)78ditext editext + (8ditext) find2iewyId(gtideditmessage)7tring message + editextgetext()totring()7intentput8xtra(8gtAM8A8 message)7

Note ltou now need import statements for androidcontentIntent andandroidwidget8ditext ltoull define the 8gtAM8A8 constant in a moment

An Intent can carry a collection of various data types as ey$value pairs called extras heput8xtra() method taes the ey name in the first parameter and the value in the secondparameter

In order for the next activity to 6uery the extra data you should define the ey for your intentsextra using a public constant o add the 8gtAM8A8 definition to the top of theMainActivity classamp

public class MainActivity extends Activity 3 public final static tring 8gtAM8A8 + comexamplemyfirstappM8A87 5

Its generally a good practice to define eys for intent extras using your apps pacage nameas a prefix his ensures they are uni6ue in case your app interacts with other apps

Start the Second Activity

o start an activity call startActivity() and pass it your Intent he system receives this call andstarts an instance of the Activity specified by the Intent

ith this new code the complete sendMessage() method thats invoed by the end button

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1316

now loos lie thisamp

11 alled when the user clics the end button 1public void sendMessage(2iew view) 3 Intent intent + new Intent(this 4isplayMessageActivityclass)7 8ditext editext + (8ditext) find2iewyId(gtideditmessage)7 tring message + editextgetext()totring()7 intentput8xtra(8gtAM8A8 message)7

startActivity(intent)75

ow you need to create the 4isplayMessageActivity class in order for this to wor

Create the Second Activity

Figure 1 he new activity wiBard in 8clipseo create a new activity using 8clipseamp

lic New in the toolbar$ In the window that appears open the Android folder and select Android Activity

lic Net- elect BlanActivity and clic NetC =ill in the activity detailsamp

bull roectamp My=irstApp

bull Activity Na$eamp 4isplayMessageActivity

bull ayout Na$eamp activitydisplaymessage

bull Titleamp My Messagebull ampierarchial arentamp comexamplemyfirstappMainActivity

bull Navigation Typeamp one

lic Finish

If youre using a different I48 or the command line tools create a new file named4isplayMessageActivity0ava in the pro0ects src directory next to the original MainActivity0avafile

pen the 4isplayMessageActivity0ava file If you used 8clipse to create this activityamp

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1416

bull he class already includes an implementation of the re6uired onreate() method

bull heres also an implementation of the onreateptionsMenu() method but you wontneed it for this app so you can remove it

bull heres also an implementation of onptionsItemelected() which handles thebehavior for the action bars Up behavior Deep this one the way it is

ecause the Actionar AEIs are available only on 8ltM (AEI level FF) and higher

you must add a condition around the getActionar() method to chec the current platformversion Additionally you must add the -uppressGint(ewApi) tag to the onreate() method to avoid lint errors

he 4isplayMessageActivity class should now loo lie thisamp

public class 4isplayMessageActivity extends Activity 3 -uppressGint(ewApi) -verride protected void onreate(undle savedInstancetate) 3 superonreate(savedInstancetate)7 setontent2iew(gtlayoutactivitydisplaymessage)7 Mae sure were running on oneycomb or higher to use Actionar AEIs

if (uild28gtI4DI + uild28gtI488ltM) 3 how the Hp button in the action bar getActionar()set4isplayomeAsHp8nabled(true)7 5 5 -verride public boolean onptionsItemelected(MenuItem item) 3 switch (itemgetItemId()) 3 case androidgtidhomeamp avHtilsnavigateHp=romameas(this)7 return true7 5 return superonptionsItemelected(item)7 55

If you used an I48 other than 8clipse update your 4isplayMessageActivity class with theabove code

All subclasses of Activity must implement the onreate() method he system calls this whencreating a new instance of the activity his method is where you must define the activitylayout with the setontent2iew() method and is where you should perform initial setup for theactivity components

Note If you are using an I48 other than 8clipse your pro0ect does not contain theactivitydisplaymessage layout thats re6uested by setontent2iew() hats D because

you will update this method later and wont be using that layout

Add the title string

If you used 8clipse you can sip to the next section because the template provides the titlestring for the new activity

If youre using an I48 other than 8clipse add the new activitys title to the stringsxml fileamp

resources

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1516

string name+titleactivitydisplaymessageMy Messagestringresources

Add it to the $aniest

All activities must be declared in your manifest file AndroidManifestxml using an activity element

hen you use the 8clipse tools to create the activity it creates a default entry If youre usinga different I48 you need to add the manifest entry yourself It should loo lie thisamp

application activity androidampname+comexamplemyfirstapp4isplayMessageActivity androidamplabel+-stringtitleactivitydisplaymessage androidampparentActivityame+comexamplemyfirstappMainActivity meta$data androidampname+androidsupportEAgt8AI2Ilt

androidampvalue+comexamplemyfirstappMainActivity activityapplication

he androidampparentActivityame attribute declares the name of this activitys parent activitywithin the apps logical hierarchy he system uses this value to implement default navigationbehaviors such as Hp navigation on Android CF (AEI level F) and higher ltou can providethe same navigation behaviors for older versions of Android by using the upport Gibrary andadding the meta$data element as shown here

Note ltour Android 4D should already include the latest Android upport Gibrary Itsincluded with the A4 undle but if youre using a different I48 you should have installed it

during the Adding Elatforms and Eacages step hen using the templates in 8clipse theupport Gibrary is automatically added to your app pro0ect (you can see the librarys JAgt filelisted under Android Dependencies) If youre not using 8clipse you need to manually add thelibrary to your pro0ectKfollow the guide for setting up the upport Gibrary then return here

If youre developing with 8clipse you can run the app now but not much happens licingthe end button starts the second activity but it uses a default ello world layout providedby the template ltoull soon update the activity to instead display a custom text view so ifyoure using a different I48 dont worry that the app wont yet compile

Receive the Intent

8very Activity is invoed by an Intent regardless of how the user navigated there ltou can getthe Intent that started your activity by calling getIntent() and retrieve the data contained withinit

In the 4isplayMessageActivity classrsquos onreate() method get the intent and extract themessage delivered by MainActivityamp

Intent intent + getIntent()7tring message + intentgettring8xtra(MainActivity8gtAM8A8)7

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1616

(isplay the )essage

o show the message on the screen create a ext2iew widget and set the text usingsetext() hen add the ext2iew as the root view of the activityrsquos layout by passing it tosetontent2iew()

he complete onreate() method for 4isplayMessageActivity now loos lie thisamp

-verridepublic void onreate(undle savedInstancetate) 3 superonreate(savedInstancetate)7 et the message from the intent Intent intent + getIntent()7 tring message + intentgettring8xtra(MainActivity8gtAM8A8)7 reate the text view ext2iew text2iew + new ext2iew(this)7 text2iewsetextiBe(CL)7 text2iewsetext(message)7 et the text view as the activity layout setontent2iew(text2iew)7

5

ltou can now run the app hen it opens type a message in the text field clic end and themessage appears on the second activity

Figure oth activities in the final app running on Android CL

Page 10: 01 Building Your First App

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1016

lt5ditext androidlayo$tweight()+) gt

n order to improe the layout efficiency when you specify the weight you should change the width of

the 5ditext to e ero (ampdp) Setting the width to ero improes layout performance ecause using

)wrapcontent) as the width re3uires the system to calculate a width that is ultimately irreleant

ecause the weight alue re3uires another width calculation to fill the remaining space

lt5ditext androidlayo$tweight()+) androidlayo$twidth()4dp) gt

igure - shows the result when you assign all weight to the 5ditext element

Figure 4 The 5ditext widget is gien all the layout weight so fills the remaining space in the

1inear1ayo$t

5eres how your complete layout file should now look

lt3xml version()+4) encoding()$t-)3gtlt1inear1ayo$t xmlnsandroid()httpschemasandroidcomapkresandroid) xmlnstools()httpschemasandroidcomtools) androidlayo$twidth()matchparent) androidlayo$theight()matchparent) androidorientation()hori2ontal)gt lt5ditext androidid()67ideditmessage) androidlayo$tweight()+)

androidlayo$twidth()4dp) androidlayo$theight()wrapcontent) androidhint()6stringeditmessage) gt lt8$tton androidlayo$twidth()wrapcontent) androidlayo$theight()wrapcontent) androidtext()6string$ttonsend) gtlt1inear1ayo$tgt

This layout is applied y the default Activity class that the SDK tools generated when you created

the project so you can now run the app to see the results

bull n Eclipse click Cun from the toolar

bull =r from a command line change directories to the root of your Android project and e4ecute

ant de$gad install inMyFirstApp-de$gapk

ontinue to the ne4t lesson to learn how you can respond to utton presses read content from the te4t

field start another actiity and more

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1116

tarting Another Acti(it)

After completing the previous lesson you have an app that shows an activity (a single screen)with a text field and a button In this lesson yoursquoll add some code to MainActivity that starts anew activity when the user clics the end button

Respond to the Send Button

o respond to the buttons on$clic event open the activitymainxml layout file and add theandroidamponlic attribute to the utton elementamp

utton androidamplayoutwidth+wrapcontent androidamplayoutheight+wrapcontent androidamptext+-stringbuttonsend androidamponlic+sendMessage

he androidamponlic attributersquos value sendMessage is the name of a method in youractivity that the system calls when the user clics the button

pen the MainActivity class (located in the pro0ects src directory) and add the correspondingmethodamp

11 alled when the user clics the end button 1public void sendMessage(2iew view) 3 4o something in response to button5

his re6uires that you import the 2iew classamp

import androidview2iew7

Tip In 8clipse press trl 9 hift 9 to import missing classes (md 9 hift 9 on Mac)

In order for the system to match this method to the method name given to androidamponlicthe signature must be exactly as shown pecifically the method mustamp

bull e public

bull ave a void return value

bull ave a 2iew as the only parameter (this will be the 2iew that was cliced)

ext yoursquoll fill in this method to read the contents of the text field and deliver that text toanother activity

Build an Intent

An Intent is an ob0ect that provides runtime binding between separate components (such astwo activities) he Intent represents an apprsquos intent to do something ltou can use intentsfor a wide variety of tass but most often theyrsquore used to start another activity

Inside the sendMessage() method create an Intent to start an activity called4isplayMessageActivityamp

Intent intent + new Intent(this 4isplayMessageActivityclass)7

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1216

he constructor used here taes two parametersamp

bull A ontext as its first parameter (this is used because the Activity class is a subclass ofontext)

bull he lass of the app component to which the system should deliver the Intent (in thiscase the activity that should be started)

Sending an intent to other apps

he intent created in this lesson is whats considered an explicit intent because the Intent specifies the exact app component to which the intent should be given owever intents canalso be implicit in which case the Intent does not specify the desired component but allowsany app installed on the device to respond to the intent as long as it satisfies the meta$dataspecifications for the action thats specified in various Intent parameters =or moreinformation see the class about Interacting with ther Apps

Note he reference to 4isplayMessageActivity will raise an error if yoursquore using an I48 suchas 8clipse because the class doesnrsquot exist yet Ignore the error for now7 yoursquoll create the classsoon

An intent not only allows you to start another activity but it can carry a bundle of data to theactivity as well Inside the sendMessage() method use find2iewyId() to get the 8ditext element and add its text value to the intentamp

Intent intent + new Intent(this 4isplayMessageActivityclass)78ditext editext + (8ditext) find2iewyId(gtideditmessage)7tring message + editextgetext()totring()7intentput8xtra(8gtAM8A8 message)7

Note ltou now need import statements for androidcontentIntent andandroidwidget8ditext ltoull define the 8gtAM8A8 constant in a moment

An Intent can carry a collection of various data types as ey$value pairs called extras heput8xtra() method taes the ey name in the first parameter and the value in the secondparameter

In order for the next activity to 6uery the extra data you should define the ey for your intentsextra using a public constant o add the 8gtAM8A8 definition to the top of theMainActivity classamp

public class MainActivity extends Activity 3 public final static tring 8gtAM8A8 + comexamplemyfirstappM8A87 5

Its generally a good practice to define eys for intent extras using your apps pacage nameas a prefix his ensures they are uni6ue in case your app interacts with other apps

Start the Second Activity

o start an activity call startActivity() and pass it your Intent he system receives this call andstarts an instance of the Activity specified by the Intent

ith this new code the complete sendMessage() method thats invoed by the end button

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1316

now loos lie thisamp

11 alled when the user clics the end button 1public void sendMessage(2iew view) 3 Intent intent + new Intent(this 4isplayMessageActivityclass)7 8ditext editext + (8ditext) find2iewyId(gtideditmessage)7 tring message + editextgetext()totring()7 intentput8xtra(8gtAM8A8 message)7

startActivity(intent)75

ow you need to create the 4isplayMessageActivity class in order for this to wor

Create the Second Activity

Figure 1 he new activity wiBard in 8clipseo create a new activity using 8clipseamp

lic New in the toolbar$ In the window that appears open the Android folder and select Android Activity

lic Net- elect BlanActivity and clic NetC =ill in the activity detailsamp

bull roectamp My=irstApp

bull Activity Na$eamp 4isplayMessageActivity

bull ayout Na$eamp activitydisplaymessage

bull Titleamp My Messagebull ampierarchial arentamp comexamplemyfirstappMainActivity

bull Navigation Typeamp one

lic Finish

If youre using a different I48 or the command line tools create a new file named4isplayMessageActivity0ava in the pro0ects src directory next to the original MainActivity0avafile

pen the 4isplayMessageActivity0ava file If you used 8clipse to create this activityamp

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1416

bull he class already includes an implementation of the re6uired onreate() method

bull heres also an implementation of the onreateptionsMenu() method but you wontneed it for this app so you can remove it

bull heres also an implementation of onptionsItemelected() which handles thebehavior for the action bars Up behavior Deep this one the way it is

ecause the Actionar AEIs are available only on 8ltM (AEI level FF) and higher

you must add a condition around the getActionar() method to chec the current platformversion Additionally you must add the -uppressGint(ewApi) tag to the onreate() method to avoid lint errors

he 4isplayMessageActivity class should now loo lie thisamp

public class 4isplayMessageActivity extends Activity 3 -uppressGint(ewApi) -verride protected void onreate(undle savedInstancetate) 3 superonreate(savedInstancetate)7 setontent2iew(gtlayoutactivitydisplaymessage)7 Mae sure were running on oneycomb or higher to use Actionar AEIs

if (uild28gtI4DI + uild28gtI488ltM) 3 how the Hp button in the action bar getActionar()set4isplayomeAsHp8nabled(true)7 5 5 -verride public boolean onptionsItemelected(MenuItem item) 3 switch (itemgetItemId()) 3 case androidgtidhomeamp avHtilsnavigateHp=romameas(this)7 return true7 5 return superonptionsItemelected(item)7 55

If you used an I48 other than 8clipse update your 4isplayMessageActivity class with theabove code

All subclasses of Activity must implement the onreate() method he system calls this whencreating a new instance of the activity his method is where you must define the activitylayout with the setontent2iew() method and is where you should perform initial setup for theactivity components

Note If you are using an I48 other than 8clipse your pro0ect does not contain theactivitydisplaymessage layout thats re6uested by setontent2iew() hats D because

you will update this method later and wont be using that layout

Add the title string

If you used 8clipse you can sip to the next section because the template provides the titlestring for the new activity

If youre using an I48 other than 8clipse add the new activitys title to the stringsxml fileamp

resources

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1516

string name+titleactivitydisplaymessageMy Messagestringresources

Add it to the $aniest

All activities must be declared in your manifest file AndroidManifestxml using an activity element

hen you use the 8clipse tools to create the activity it creates a default entry If youre usinga different I48 you need to add the manifest entry yourself It should loo lie thisamp

application activity androidampname+comexamplemyfirstapp4isplayMessageActivity androidamplabel+-stringtitleactivitydisplaymessage androidampparentActivityame+comexamplemyfirstappMainActivity meta$data androidampname+androidsupportEAgt8AI2Ilt

androidampvalue+comexamplemyfirstappMainActivity activityapplication

he androidampparentActivityame attribute declares the name of this activitys parent activitywithin the apps logical hierarchy he system uses this value to implement default navigationbehaviors such as Hp navigation on Android CF (AEI level F) and higher ltou can providethe same navigation behaviors for older versions of Android by using the upport Gibrary andadding the meta$data element as shown here

Note ltour Android 4D should already include the latest Android upport Gibrary Itsincluded with the A4 undle but if youre using a different I48 you should have installed it

during the Adding Elatforms and Eacages step hen using the templates in 8clipse theupport Gibrary is automatically added to your app pro0ect (you can see the librarys JAgt filelisted under Android Dependencies) If youre not using 8clipse you need to manually add thelibrary to your pro0ectKfollow the guide for setting up the upport Gibrary then return here

If youre developing with 8clipse you can run the app now but not much happens licingthe end button starts the second activity but it uses a default ello world layout providedby the template ltoull soon update the activity to instead display a custom text view so ifyoure using a different I48 dont worry that the app wont yet compile

Receive the Intent

8very Activity is invoed by an Intent regardless of how the user navigated there ltou can getthe Intent that started your activity by calling getIntent() and retrieve the data contained withinit

In the 4isplayMessageActivity classrsquos onreate() method get the intent and extract themessage delivered by MainActivityamp

Intent intent + getIntent()7tring message + intentgettring8xtra(MainActivity8gtAM8A8)7

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1616

(isplay the )essage

o show the message on the screen create a ext2iew widget and set the text usingsetext() hen add the ext2iew as the root view of the activityrsquos layout by passing it tosetontent2iew()

he complete onreate() method for 4isplayMessageActivity now loos lie thisamp

-verridepublic void onreate(undle savedInstancetate) 3 superonreate(savedInstancetate)7 et the message from the intent Intent intent + getIntent()7 tring message + intentgettring8xtra(MainActivity8gtAM8A8)7 reate the text view ext2iew text2iew + new ext2iew(this)7 text2iewsetextiBe(CL)7 text2iewsetext(message)7 et the text view as the activity layout setontent2iew(text2iew)7

5

ltou can now run the app hen it opens type a message in the text field clic end and themessage appears on the second activity

Figure oth activities in the final app running on Android CL

Page 11: 01 Building Your First App

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1116

tarting Another Acti(it)

After completing the previous lesson you have an app that shows an activity (a single screen)with a text field and a button In this lesson yoursquoll add some code to MainActivity that starts anew activity when the user clics the end button

Respond to the Send Button

o respond to the buttons on$clic event open the activitymainxml layout file and add theandroidamponlic attribute to the utton elementamp

utton androidamplayoutwidth+wrapcontent androidamplayoutheight+wrapcontent androidamptext+-stringbuttonsend androidamponlic+sendMessage

he androidamponlic attributersquos value sendMessage is the name of a method in youractivity that the system calls when the user clics the button

pen the MainActivity class (located in the pro0ects src directory) and add the correspondingmethodamp

11 alled when the user clics the end button 1public void sendMessage(2iew view) 3 4o something in response to button5

his re6uires that you import the 2iew classamp

import androidview2iew7

Tip In 8clipse press trl 9 hift 9 to import missing classes (md 9 hift 9 on Mac)

In order for the system to match this method to the method name given to androidamponlicthe signature must be exactly as shown pecifically the method mustamp

bull e public

bull ave a void return value

bull ave a 2iew as the only parameter (this will be the 2iew that was cliced)

ext yoursquoll fill in this method to read the contents of the text field and deliver that text toanother activity

Build an Intent

An Intent is an ob0ect that provides runtime binding between separate components (such astwo activities) he Intent represents an apprsquos intent to do something ltou can use intentsfor a wide variety of tass but most often theyrsquore used to start another activity

Inside the sendMessage() method create an Intent to start an activity called4isplayMessageActivityamp

Intent intent + new Intent(this 4isplayMessageActivityclass)7

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1216

he constructor used here taes two parametersamp

bull A ontext as its first parameter (this is used because the Activity class is a subclass ofontext)

bull he lass of the app component to which the system should deliver the Intent (in thiscase the activity that should be started)

Sending an intent to other apps

he intent created in this lesson is whats considered an explicit intent because the Intent specifies the exact app component to which the intent should be given owever intents canalso be implicit in which case the Intent does not specify the desired component but allowsany app installed on the device to respond to the intent as long as it satisfies the meta$dataspecifications for the action thats specified in various Intent parameters =or moreinformation see the class about Interacting with ther Apps

Note he reference to 4isplayMessageActivity will raise an error if yoursquore using an I48 suchas 8clipse because the class doesnrsquot exist yet Ignore the error for now7 yoursquoll create the classsoon

An intent not only allows you to start another activity but it can carry a bundle of data to theactivity as well Inside the sendMessage() method use find2iewyId() to get the 8ditext element and add its text value to the intentamp

Intent intent + new Intent(this 4isplayMessageActivityclass)78ditext editext + (8ditext) find2iewyId(gtideditmessage)7tring message + editextgetext()totring()7intentput8xtra(8gtAM8A8 message)7

Note ltou now need import statements for androidcontentIntent andandroidwidget8ditext ltoull define the 8gtAM8A8 constant in a moment

An Intent can carry a collection of various data types as ey$value pairs called extras heput8xtra() method taes the ey name in the first parameter and the value in the secondparameter

In order for the next activity to 6uery the extra data you should define the ey for your intentsextra using a public constant o add the 8gtAM8A8 definition to the top of theMainActivity classamp

public class MainActivity extends Activity 3 public final static tring 8gtAM8A8 + comexamplemyfirstappM8A87 5

Its generally a good practice to define eys for intent extras using your apps pacage nameas a prefix his ensures they are uni6ue in case your app interacts with other apps

Start the Second Activity

o start an activity call startActivity() and pass it your Intent he system receives this call andstarts an instance of the Activity specified by the Intent

ith this new code the complete sendMessage() method thats invoed by the end button

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1316

now loos lie thisamp

11 alled when the user clics the end button 1public void sendMessage(2iew view) 3 Intent intent + new Intent(this 4isplayMessageActivityclass)7 8ditext editext + (8ditext) find2iewyId(gtideditmessage)7 tring message + editextgetext()totring()7 intentput8xtra(8gtAM8A8 message)7

startActivity(intent)75

ow you need to create the 4isplayMessageActivity class in order for this to wor

Create the Second Activity

Figure 1 he new activity wiBard in 8clipseo create a new activity using 8clipseamp

lic New in the toolbar$ In the window that appears open the Android folder and select Android Activity

lic Net- elect BlanActivity and clic NetC =ill in the activity detailsamp

bull roectamp My=irstApp

bull Activity Na$eamp 4isplayMessageActivity

bull ayout Na$eamp activitydisplaymessage

bull Titleamp My Messagebull ampierarchial arentamp comexamplemyfirstappMainActivity

bull Navigation Typeamp one

lic Finish

If youre using a different I48 or the command line tools create a new file named4isplayMessageActivity0ava in the pro0ects src directory next to the original MainActivity0avafile

pen the 4isplayMessageActivity0ava file If you used 8clipse to create this activityamp

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1416

bull he class already includes an implementation of the re6uired onreate() method

bull heres also an implementation of the onreateptionsMenu() method but you wontneed it for this app so you can remove it

bull heres also an implementation of onptionsItemelected() which handles thebehavior for the action bars Up behavior Deep this one the way it is

ecause the Actionar AEIs are available only on 8ltM (AEI level FF) and higher

you must add a condition around the getActionar() method to chec the current platformversion Additionally you must add the -uppressGint(ewApi) tag to the onreate() method to avoid lint errors

he 4isplayMessageActivity class should now loo lie thisamp

public class 4isplayMessageActivity extends Activity 3 -uppressGint(ewApi) -verride protected void onreate(undle savedInstancetate) 3 superonreate(savedInstancetate)7 setontent2iew(gtlayoutactivitydisplaymessage)7 Mae sure were running on oneycomb or higher to use Actionar AEIs

if (uild28gtI4DI + uild28gtI488ltM) 3 how the Hp button in the action bar getActionar()set4isplayomeAsHp8nabled(true)7 5 5 -verride public boolean onptionsItemelected(MenuItem item) 3 switch (itemgetItemId()) 3 case androidgtidhomeamp avHtilsnavigateHp=romameas(this)7 return true7 5 return superonptionsItemelected(item)7 55

If you used an I48 other than 8clipse update your 4isplayMessageActivity class with theabove code

All subclasses of Activity must implement the onreate() method he system calls this whencreating a new instance of the activity his method is where you must define the activitylayout with the setontent2iew() method and is where you should perform initial setup for theactivity components

Note If you are using an I48 other than 8clipse your pro0ect does not contain theactivitydisplaymessage layout thats re6uested by setontent2iew() hats D because

you will update this method later and wont be using that layout

Add the title string

If you used 8clipse you can sip to the next section because the template provides the titlestring for the new activity

If youre using an I48 other than 8clipse add the new activitys title to the stringsxml fileamp

resources

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1516

string name+titleactivitydisplaymessageMy Messagestringresources

Add it to the $aniest

All activities must be declared in your manifest file AndroidManifestxml using an activity element

hen you use the 8clipse tools to create the activity it creates a default entry If youre usinga different I48 you need to add the manifest entry yourself It should loo lie thisamp

application activity androidampname+comexamplemyfirstapp4isplayMessageActivity androidamplabel+-stringtitleactivitydisplaymessage androidampparentActivityame+comexamplemyfirstappMainActivity meta$data androidampname+androidsupportEAgt8AI2Ilt

androidampvalue+comexamplemyfirstappMainActivity activityapplication

he androidampparentActivityame attribute declares the name of this activitys parent activitywithin the apps logical hierarchy he system uses this value to implement default navigationbehaviors such as Hp navigation on Android CF (AEI level F) and higher ltou can providethe same navigation behaviors for older versions of Android by using the upport Gibrary andadding the meta$data element as shown here

Note ltour Android 4D should already include the latest Android upport Gibrary Itsincluded with the A4 undle but if youre using a different I48 you should have installed it

during the Adding Elatforms and Eacages step hen using the templates in 8clipse theupport Gibrary is automatically added to your app pro0ect (you can see the librarys JAgt filelisted under Android Dependencies) If youre not using 8clipse you need to manually add thelibrary to your pro0ectKfollow the guide for setting up the upport Gibrary then return here

If youre developing with 8clipse you can run the app now but not much happens licingthe end button starts the second activity but it uses a default ello world layout providedby the template ltoull soon update the activity to instead display a custom text view so ifyoure using a different I48 dont worry that the app wont yet compile

Receive the Intent

8very Activity is invoed by an Intent regardless of how the user navigated there ltou can getthe Intent that started your activity by calling getIntent() and retrieve the data contained withinit

In the 4isplayMessageActivity classrsquos onreate() method get the intent and extract themessage delivered by MainActivityamp

Intent intent + getIntent()7tring message + intentgettring8xtra(MainActivity8gtAM8A8)7

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1616

(isplay the )essage

o show the message on the screen create a ext2iew widget and set the text usingsetext() hen add the ext2iew as the root view of the activityrsquos layout by passing it tosetontent2iew()

he complete onreate() method for 4isplayMessageActivity now loos lie thisamp

-verridepublic void onreate(undle savedInstancetate) 3 superonreate(savedInstancetate)7 et the message from the intent Intent intent + getIntent()7 tring message + intentgettring8xtra(MainActivity8gtAM8A8)7 reate the text view ext2iew text2iew + new ext2iew(this)7 text2iewsetextiBe(CL)7 text2iewsetext(message)7 et the text view as the activity layout setontent2iew(text2iew)7

5

ltou can now run the app hen it opens type a message in the text field clic end and themessage appears on the second activity

Figure oth activities in the final app running on Android CL

Page 12: 01 Building Your First App

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1216

he constructor used here taes two parametersamp

bull A ontext as its first parameter (this is used because the Activity class is a subclass ofontext)

bull he lass of the app component to which the system should deliver the Intent (in thiscase the activity that should be started)

Sending an intent to other apps

he intent created in this lesson is whats considered an explicit intent because the Intent specifies the exact app component to which the intent should be given owever intents canalso be implicit in which case the Intent does not specify the desired component but allowsany app installed on the device to respond to the intent as long as it satisfies the meta$dataspecifications for the action thats specified in various Intent parameters =or moreinformation see the class about Interacting with ther Apps

Note he reference to 4isplayMessageActivity will raise an error if yoursquore using an I48 suchas 8clipse because the class doesnrsquot exist yet Ignore the error for now7 yoursquoll create the classsoon

An intent not only allows you to start another activity but it can carry a bundle of data to theactivity as well Inside the sendMessage() method use find2iewyId() to get the 8ditext element and add its text value to the intentamp

Intent intent + new Intent(this 4isplayMessageActivityclass)78ditext editext + (8ditext) find2iewyId(gtideditmessage)7tring message + editextgetext()totring()7intentput8xtra(8gtAM8A8 message)7

Note ltou now need import statements for androidcontentIntent andandroidwidget8ditext ltoull define the 8gtAM8A8 constant in a moment

An Intent can carry a collection of various data types as ey$value pairs called extras heput8xtra() method taes the ey name in the first parameter and the value in the secondparameter

In order for the next activity to 6uery the extra data you should define the ey for your intentsextra using a public constant o add the 8gtAM8A8 definition to the top of theMainActivity classamp

public class MainActivity extends Activity 3 public final static tring 8gtAM8A8 + comexamplemyfirstappM8A87 5

Its generally a good practice to define eys for intent extras using your apps pacage nameas a prefix his ensures they are uni6ue in case your app interacts with other apps

Start the Second Activity

o start an activity call startActivity() and pass it your Intent he system receives this call andstarts an instance of the Activity specified by the Intent

ith this new code the complete sendMessage() method thats invoed by the end button

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1316

now loos lie thisamp

11 alled when the user clics the end button 1public void sendMessage(2iew view) 3 Intent intent + new Intent(this 4isplayMessageActivityclass)7 8ditext editext + (8ditext) find2iewyId(gtideditmessage)7 tring message + editextgetext()totring()7 intentput8xtra(8gtAM8A8 message)7

startActivity(intent)75

ow you need to create the 4isplayMessageActivity class in order for this to wor

Create the Second Activity

Figure 1 he new activity wiBard in 8clipseo create a new activity using 8clipseamp

lic New in the toolbar$ In the window that appears open the Android folder and select Android Activity

lic Net- elect BlanActivity and clic NetC =ill in the activity detailsamp

bull roectamp My=irstApp

bull Activity Na$eamp 4isplayMessageActivity

bull ayout Na$eamp activitydisplaymessage

bull Titleamp My Messagebull ampierarchial arentamp comexamplemyfirstappMainActivity

bull Navigation Typeamp one

lic Finish

If youre using a different I48 or the command line tools create a new file named4isplayMessageActivity0ava in the pro0ects src directory next to the original MainActivity0avafile

pen the 4isplayMessageActivity0ava file If you used 8clipse to create this activityamp

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1416

bull he class already includes an implementation of the re6uired onreate() method

bull heres also an implementation of the onreateptionsMenu() method but you wontneed it for this app so you can remove it

bull heres also an implementation of onptionsItemelected() which handles thebehavior for the action bars Up behavior Deep this one the way it is

ecause the Actionar AEIs are available only on 8ltM (AEI level FF) and higher

you must add a condition around the getActionar() method to chec the current platformversion Additionally you must add the -uppressGint(ewApi) tag to the onreate() method to avoid lint errors

he 4isplayMessageActivity class should now loo lie thisamp

public class 4isplayMessageActivity extends Activity 3 -uppressGint(ewApi) -verride protected void onreate(undle savedInstancetate) 3 superonreate(savedInstancetate)7 setontent2iew(gtlayoutactivitydisplaymessage)7 Mae sure were running on oneycomb or higher to use Actionar AEIs

if (uild28gtI4DI + uild28gtI488ltM) 3 how the Hp button in the action bar getActionar()set4isplayomeAsHp8nabled(true)7 5 5 -verride public boolean onptionsItemelected(MenuItem item) 3 switch (itemgetItemId()) 3 case androidgtidhomeamp avHtilsnavigateHp=romameas(this)7 return true7 5 return superonptionsItemelected(item)7 55

If you used an I48 other than 8clipse update your 4isplayMessageActivity class with theabove code

All subclasses of Activity must implement the onreate() method he system calls this whencreating a new instance of the activity his method is where you must define the activitylayout with the setontent2iew() method and is where you should perform initial setup for theactivity components

Note If you are using an I48 other than 8clipse your pro0ect does not contain theactivitydisplaymessage layout thats re6uested by setontent2iew() hats D because

you will update this method later and wont be using that layout

Add the title string

If you used 8clipse you can sip to the next section because the template provides the titlestring for the new activity

If youre using an I48 other than 8clipse add the new activitys title to the stringsxml fileamp

resources

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1516

string name+titleactivitydisplaymessageMy Messagestringresources

Add it to the $aniest

All activities must be declared in your manifest file AndroidManifestxml using an activity element

hen you use the 8clipse tools to create the activity it creates a default entry If youre usinga different I48 you need to add the manifest entry yourself It should loo lie thisamp

application activity androidampname+comexamplemyfirstapp4isplayMessageActivity androidamplabel+-stringtitleactivitydisplaymessage androidampparentActivityame+comexamplemyfirstappMainActivity meta$data androidampname+androidsupportEAgt8AI2Ilt

androidampvalue+comexamplemyfirstappMainActivity activityapplication

he androidampparentActivityame attribute declares the name of this activitys parent activitywithin the apps logical hierarchy he system uses this value to implement default navigationbehaviors such as Hp navigation on Android CF (AEI level F) and higher ltou can providethe same navigation behaviors for older versions of Android by using the upport Gibrary andadding the meta$data element as shown here

Note ltour Android 4D should already include the latest Android upport Gibrary Itsincluded with the A4 undle but if youre using a different I48 you should have installed it

during the Adding Elatforms and Eacages step hen using the templates in 8clipse theupport Gibrary is automatically added to your app pro0ect (you can see the librarys JAgt filelisted under Android Dependencies) If youre not using 8clipse you need to manually add thelibrary to your pro0ectKfollow the guide for setting up the upport Gibrary then return here

If youre developing with 8clipse you can run the app now but not much happens licingthe end button starts the second activity but it uses a default ello world layout providedby the template ltoull soon update the activity to instead display a custom text view so ifyoure using a different I48 dont worry that the app wont yet compile

Receive the Intent

8very Activity is invoed by an Intent regardless of how the user navigated there ltou can getthe Intent that started your activity by calling getIntent() and retrieve the data contained withinit

In the 4isplayMessageActivity classrsquos onreate() method get the intent and extract themessage delivered by MainActivityamp

Intent intent + getIntent()7tring message + intentgettring8xtra(MainActivity8gtAM8A8)7

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1616

(isplay the )essage

o show the message on the screen create a ext2iew widget and set the text usingsetext() hen add the ext2iew as the root view of the activityrsquos layout by passing it tosetontent2iew()

he complete onreate() method for 4isplayMessageActivity now loos lie thisamp

-verridepublic void onreate(undle savedInstancetate) 3 superonreate(savedInstancetate)7 et the message from the intent Intent intent + getIntent()7 tring message + intentgettring8xtra(MainActivity8gtAM8A8)7 reate the text view ext2iew text2iew + new ext2iew(this)7 text2iewsetextiBe(CL)7 text2iewsetext(message)7 et the text view as the activity layout setontent2iew(text2iew)7

5

ltou can now run the app hen it opens type a message in the text field clic end and themessage appears on the second activity

Figure oth activities in the final app running on Android CL

Page 13: 01 Building Your First App

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1316

now loos lie thisamp

11 alled when the user clics the end button 1public void sendMessage(2iew view) 3 Intent intent + new Intent(this 4isplayMessageActivityclass)7 8ditext editext + (8ditext) find2iewyId(gtideditmessage)7 tring message + editextgetext()totring()7 intentput8xtra(8gtAM8A8 message)7

startActivity(intent)75

ow you need to create the 4isplayMessageActivity class in order for this to wor

Create the Second Activity

Figure 1 he new activity wiBard in 8clipseo create a new activity using 8clipseamp

lic New in the toolbar$ In the window that appears open the Android folder and select Android Activity

lic Net- elect BlanActivity and clic NetC =ill in the activity detailsamp

bull roectamp My=irstApp

bull Activity Na$eamp 4isplayMessageActivity

bull ayout Na$eamp activitydisplaymessage

bull Titleamp My Messagebull ampierarchial arentamp comexamplemyfirstappMainActivity

bull Navigation Typeamp one

lic Finish

If youre using a different I48 or the command line tools create a new file named4isplayMessageActivity0ava in the pro0ects src directory next to the original MainActivity0avafile

pen the 4isplayMessageActivity0ava file If you used 8clipse to create this activityamp

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1416

bull he class already includes an implementation of the re6uired onreate() method

bull heres also an implementation of the onreateptionsMenu() method but you wontneed it for this app so you can remove it

bull heres also an implementation of onptionsItemelected() which handles thebehavior for the action bars Up behavior Deep this one the way it is

ecause the Actionar AEIs are available only on 8ltM (AEI level FF) and higher

you must add a condition around the getActionar() method to chec the current platformversion Additionally you must add the -uppressGint(ewApi) tag to the onreate() method to avoid lint errors

he 4isplayMessageActivity class should now loo lie thisamp

public class 4isplayMessageActivity extends Activity 3 -uppressGint(ewApi) -verride protected void onreate(undle savedInstancetate) 3 superonreate(savedInstancetate)7 setontent2iew(gtlayoutactivitydisplaymessage)7 Mae sure were running on oneycomb or higher to use Actionar AEIs

if (uild28gtI4DI + uild28gtI488ltM) 3 how the Hp button in the action bar getActionar()set4isplayomeAsHp8nabled(true)7 5 5 -verride public boolean onptionsItemelected(MenuItem item) 3 switch (itemgetItemId()) 3 case androidgtidhomeamp avHtilsnavigateHp=romameas(this)7 return true7 5 return superonptionsItemelected(item)7 55

If you used an I48 other than 8clipse update your 4isplayMessageActivity class with theabove code

All subclasses of Activity must implement the onreate() method he system calls this whencreating a new instance of the activity his method is where you must define the activitylayout with the setontent2iew() method and is where you should perform initial setup for theactivity components

Note If you are using an I48 other than 8clipse your pro0ect does not contain theactivitydisplaymessage layout thats re6uested by setontent2iew() hats D because

you will update this method later and wont be using that layout

Add the title string

If you used 8clipse you can sip to the next section because the template provides the titlestring for the new activity

If youre using an I48 other than 8clipse add the new activitys title to the stringsxml fileamp

resources

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1516

string name+titleactivitydisplaymessageMy Messagestringresources

Add it to the $aniest

All activities must be declared in your manifest file AndroidManifestxml using an activity element

hen you use the 8clipse tools to create the activity it creates a default entry If youre usinga different I48 you need to add the manifest entry yourself It should loo lie thisamp

application activity androidampname+comexamplemyfirstapp4isplayMessageActivity androidamplabel+-stringtitleactivitydisplaymessage androidampparentActivityame+comexamplemyfirstappMainActivity meta$data androidampname+androidsupportEAgt8AI2Ilt

androidampvalue+comexamplemyfirstappMainActivity activityapplication

he androidampparentActivityame attribute declares the name of this activitys parent activitywithin the apps logical hierarchy he system uses this value to implement default navigationbehaviors such as Hp navigation on Android CF (AEI level F) and higher ltou can providethe same navigation behaviors for older versions of Android by using the upport Gibrary andadding the meta$data element as shown here

Note ltour Android 4D should already include the latest Android upport Gibrary Itsincluded with the A4 undle but if youre using a different I48 you should have installed it

during the Adding Elatforms and Eacages step hen using the templates in 8clipse theupport Gibrary is automatically added to your app pro0ect (you can see the librarys JAgt filelisted under Android Dependencies) If youre not using 8clipse you need to manually add thelibrary to your pro0ectKfollow the guide for setting up the upport Gibrary then return here

If youre developing with 8clipse you can run the app now but not much happens licingthe end button starts the second activity but it uses a default ello world layout providedby the template ltoull soon update the activity to instead display a custom text view so ifyoure using a different I48 dont worry that the app wont yet compile

Receive the Intent

8very Activity is invoed by an Intent regardless of how the user navigated there ltou can getthe Intent that started your activity by calling getIntent() and retrieve the data contained withinit

In the 4isplayMessageActivity classrsquos onreate() method get the intent and extract themessage delivered by MainActivityamp

Intent intent + getIntent()7tring message + intentgettring8xtra(MainActivity8gtAM8A8)7

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1616

(isplay the )essage

o show the message on the screen create a ext2iew widget and set the text usingsetext() hen add the ext2iew as the root view of the activityrsquos layout by passing it tosetontent2iew()

he complete onreate() method for 4isplayMessageActivity now loos lie thisamp

-verridepublic void onreate(undle savedInstancetate) 3 superonreate(savedInstancetate)7 et the message from the intent Intent intent + getIntent()7 tring message + intentgettring8xtra(MainActivity8gtAM8A8)7 reate the text view ext2iew text2iew + new ext2iew(this)7 text2iewsetextiBe(CL)7 text2iewsetext(message)7 et the text view as the activity layout setontent2iew(text2iew)7

5

ltou can now run the app hen it opens type a message in the text field clic end and themessage appears on the second activity

Figure oth activities in the final app running on Android CL

Page 14: 01 Building Your First App

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1416

bull he class already includes an implementation of the re6uired onreate() method

bull heres also an implementation of the onreateptionsMenu() method but you wontneed it for this app so you can remove it

bull heres also an implementation of onptionsItemelected() which handles thebehavior for the action bars Up behavior Deep this one the way it is

ecause the Actionar AEIs are available only on 8ltM (AEI level FF) and higher

you must add a condition around the getActionar() method to chec the current platformversion Additionally you must add the -uppressGint(ewApi) tag to the onreate() method to avoid lint errors

he 4isplayMessageActivity class should now loo lie thisamp

public class 4isplayMessageActivity extends Activity 3 -uppressGint(ewApi) -verride protected void onreate(undle savedInstancetate) 3 superonreate(savedInstancetate)7 setontent2iew(gtlayoutactivitydisplaymessage)7 Mae sure were running on oneycomb or higher to use Actionar AEIs

if (uild28gtI4DI + uild28gtI488ltM) 3 how the Hp button in the action bar getActionar()set4isplayomeAsHp8nabled(true)7 5 5 -verride public boolean onptionsItemelected(MenuItem item) 3 switch (itemgetItemId()) 3 case androidgtidhomeamp avHtilsnavigateHp=romameas(this)7 return true7 5 return superonptionsItemelected(item)7 55

If you used an I48 other than 8clipse update your 4isplayMessageActivity class with theabove code

All subclasses of Activity must implement the onreate() method he system calls this whencreating a new instance of the activity his method is where you must define the activitylayout with the setontent2iew() method and is where you should perform initial setup for theactivity components

Note If you are using an I48 other than 8clipse your pro0ect does not contain theactivitydisplaymessage layout thats re6uested by setontent2iew() hats D because

you will update this method later and wont be using that layout

Add the title string

If you used 8clipse you can sip to the next section because the template provides the titlestring for the new activity

If youre using an I48 other than 8clipse add the new activitys title to the stringsxml fileamp

resources

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1516

string name+titleactivitydisplaymessageMy Messagestringresources

Add it to the $aniest

All activities must be declared in your manifest file AndroidManifestxml using an activity element

hen you use the 8clipse tools to create the activity it creates a default entry If youre usinga different I48 you need to add the manifest entry yourself It should loo lie thisamp

application activity androidampname+comexamplemyfirstapp4isplayMessageActivity androidamplabel+-stringtitleactivitydisplaymessage androidampparentActivityame+comexamplemyfirstappMainActivity meta$data androidampname+androidsupportEAgt8AI2Ilt

androidampvalue+comexamplemyfirstappMainActivity activityapplication

he androidampparentActivityame attribute declares the name of this activitys parent activitywithin the apps logical hierarchy he system uses this value to implement default navigationbehaviors such as Hp navigation on Android CF (AEI level F) and higher ltou can providethe same navigation behaviors for older versions of Android by using the upport Gibrary andadding the meta$data element as shown here

Note ltour Android 4D should already include the latest Android upport Gibrary Itsincluded with the A4 undle but if youre using a different I48 you should have installed it

during the Adding Elatforms and Eacages step hen using the templates in 8clipse theupport Gibrary is automatically added to your app pro0ect (you can see the librarys JAgt filelisted under Android Dependencies) If youre not using 8clipse you need to manually add thelibrary to your pro0ectKfollow the guide for setting up the upport Gibrary then return here

If youre developing with 8clipse you can run the app now but not much happens licingthe end button starts the second activity but it uses a default ello world layout providedby the template ltoull soon update the activity to instead display a custom text view so ifyoure using a different I48 dont worry that the app wont yet compile

Receive the Intent

8very Activity is invoed by an Intent regardless of how the user navigated there ltou can getthe Intent that started your activity by calling getIntent() and retrieve the data contained withinit

In the 4isplayMessageActivity classrsquos onreate() method get the intent and extract themessage delivered by MainActivityamp

Intent intent + getIntent()7tring message + intentgettring8xtra(MainActivity8gtAM8A8)7

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1616

(isplay the )essage

o show the message on the screen create a ext2iew widget and set the text usingsetext() hen add the ext2iew as the root view of the activityrsquos layout by passing it tosetontent2iew()

he complete onreate() method for 4isplayMessageActivity now loos lie thisamp

-verridepublic void onreate(undle savedInstancetate) 3 superonreate(savedInstancetate)7 et the message from the intent Intent intent + getIntent()7 tring message + intentgettring8xtra(MainActivity8gtAM8A8)7 reate the text view ext2iew text2iew + new ext2iew(this)7 text2iewsetextiBe(CL)7 text2iewsetext(message)7 et the text view as the activity layout setontent2iew(text2iew)7

5

ltou can now run the app hen it opens type a message in the text field clic end and themessage appears on the second activity

Figure oth activities in the final app running on Android CL

Page 15: 01 Building Your First App

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1516

string name+titleactivitydisplaymessageMy Messagestringresources

Add it to the $aniest

All activities must be declared in your manifest file AndroidManifestxml using an activity element

hen you use the 8clipse tools to create the activity it creates a default entry If youre usinga different I48 you need to add the manifest entry yourself It should loo lie thisamp

application activity androidampname+comexamplemyfirstapp4isplayMessageActivity androidamplabel+-stringtitleactivitydisplaymessage androidampparentActivityame+comexamplemyfirstappMainActivity meta$data androidampname+androidsupportEAgt8AI2Ilt

androidampvalue+comexamplemyfirstappMainActivity activityapplication

he androidampparentActivityame attribute declares the name of this activitys parent activitywithin the apps logical hierarchy he system uses this value to implement default navigationbehaviors such as Hp navigation on Android CF (AEI level F) and higher ltou can providethe same navigation behaviors for older versions of Android by using the upport Gibrary andadding the meta$data element as shown here

Note ltour Android 4D should already include the latest Android upport Gibrary Itsincluded with the A4 undle but if youre using a different I48 you should have installed it

during the Adding Elatforms and Eacages step hen using the templates in 8clipse theupport Gibrary is automatically added to your app pro0ect (you can see the librarys JAgt filelisted under Android Dependencies) If youre not using 8clipse you need to manually add thelibrary to your pro0ectKfollow the guide for setting up the upport Gibrary then return here

If youre developing with 8clipse you can run the app now but not much happens licingthe end button starts the second activity but it uses a default ello world layout providedby the template ltoull soon update the activity to instead display a custom text view so ifyoure using a different I48 dont worry that the app wont yet compile

Receive the Intent

8very Activity is invoed by an Intent regardless of how the user navigated there ltou can getthe Intent that started your activity by calling getIntent() and retrieve the data contained withinit

In the 4isplayMessageActivity classrsquos onreate() method get the intent and extract themessage delivered by MainActivityamp

Intent intent + getIntent()7tring message + intentgettring8xtra(MainActivity8gtAM8A8)7

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1616

(isplay the )essage

o show the message on the screen create a ext2iew widget and set the text usingsetext() hen add the ext2iew as the root view of the activityrsquos layout by passing it tosetontent2iew()

he complete onreate() method for 4isplayMessageActivity now loos lie thisamp

-verridepublic void onreate(undle savedInstancetate) 3 superonreate(savedInstancetate)7 et the message from the intent Intent intent + getIntent()7 tring message + intentgettring8xtra(MainActivity8gtAM8A8)7 reate the text view ext2iew text2iew + new ext2iew(this)7 text2iewsetextiBe(CL)7 text2iewsetext(message)7 et the text view as the activity layout setontent2iew(text2iew)7

5

ltou can now run the app hen it opens type a message in the text field clic end and themessage appears on the second activity

Figure oth activities in the final app running on Android CL

Page 16: 01 Building Your First App

8132019 01 Building Your First App

httpslidepdfcomreaderfull01-building-your-first-app 1616

(isplay the )essage

o show the message on the screen create a ext2iew widget and set the text usingsetext() hen add the ext2iew as the root view of the activityrsquos layout by passing it tosetontent2iew()

he complete onreate() method for 4isplayMessageActivity now loos lie thisamp

-verridepublic void onreate(undle savedInstancetate) 3 superonreate(savedInstancetate)7 et the message from the intent Intent intent + getIntent()7 tring message + intentgettring8xtra(MainActivity8gtAM8A8)7 reate the text view ext2iew text2iew + new ext2iew(this)7 text2iewsetextiBe(CL)7 text2iewsetext(message)7 et the text view as the activity layout setontent2iew(text2iew)7

5

ltou can now run the app hen it opens type a message in the text field clic end and themessage appears on the second activity

Figure oth activities in the final app running on Android CL