Survey							
                            
		                
		                * Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
CSCE 315: Android Lectures (2/2)
• Dr. Jaerock Kwon
• Kettering University
App Development for Mobile Devices
Jaerock Kwon, Ph.D. Assistant Professor in Computer Engineering
App Development for Mobile Devices
Kettering University
Jaerock Kwon, Ph.D. Assistant Professor in Computer Engineering
1
Announcement
2
3
Announcement
Lecture 2
Application Fundamentals
Kettering University
Kettering University
2
Today’s Topics
4
5
  Android development tools
  Virtual Device Manager
  Android Emulator
Android Development Tools
  Dalvik Debug Monitoring Service
  Application components
  Activity
  Service
Android Development Tools
  Broadcast receiver
  Content provider
Kettering University
  Intent
  App manifest
  Application resources
Kettering University
Virtual Device Manager
  Create and manage Android Virtual Devices
  Window menu item in Eclipse – Android SDK and AVD Manager
  You can start Android Emulator from the AVD Manager.
Kettering University
6
Android Emulator
  An implementation of the Android virtual machine.
5
Virtual Device Manager
  Use this to test and debug your Android applications.
  Create and manage Android Virtual Devices
  Window menu item in Eclipse – Android SDK and AVD Manager
  You can start Android Emulator from the AVD Manager.
Android Development Tools
Kettering University
7
Kettering University
6
  Written in Java
Dalvik Debug Monitoring Service
8
  The compiled Java code along with resource files and data is
bundled by aapt tool into an Android package.
9
  aapt (Android Asset Packaging Tool)
  Probably you will not use this directly.
  Use the DDMS perspective to monitor and control Dalvik virtual
machines on which you are debugging your apps.
  IDE plugins utilizes this tool to package the apk file.
  Android package:
  A single archive file. Its filename extension is .apk.
  This apk file is the file that users download to their devices.
  Linux process
  Every application runs in its own Linux process.
Android Applications
  Each process has its own virtual machine.
Kettering University
Kettering University
Kettering University
Android Application
10
  Written in Java
  The compiled Java code along with resource files and data is
bundled by aapt tool into an Android package.
  aapt (Android Asset Packaging Tool)
  Probably you will not use this directly.
  IDE plugins utilizes this tool to package the apk file.
  Android package:
  A single archive file. Its filename extension is .apk.
  This apk file is the file that users download to their devices.
  Every application runs in its own Linux process.
Android Applications
  Each process has its own virtual machine.
11
  An application can use elements of other applications (should be
permitted by the apps).
  For this to work, an application process can be started when any part of
it is needed and instantiate the Java objects for that part.
  Therefore, Android apps don’t have a single entry point (like main()
function).
  Rather they have essential components that the system can instantiate
and run as needed.
  Four types of components
  Activities
  Services
  Linux process
Kettering University
9
Central Features of Android
  Broadcast receivers
  Content providers
Kettering University
  No visual interface.
  Application’s presentation layer.
  Every screen in you app is an extension of the Activity class.
12
Activities
  Runs in the background of an indefinite period of time.
13
  Each activity is given a default window to draw in.
  Examples:
  Activities use Views to form GUI.
  Application’s presentation layer.
  Each service extends the Service base class
  Every screen in you app is an extension of the Activity class.
  It is possible to connect to an ongoing service (and start the service
if it is not
already
running).
  Each
activity
is given
a default window to draw in.
  Play background music, fetch data over the network.
  Each view controls a particular rectangular space within the window.
  Views are where the activity’s interaction with the user takes place.
  ContentView is the root view object in the hierarchy of views.
  You can communicate with service through an interface that the service
  Activity.setContentView() method.
exposes.use Views to form GUI.
  Activities
  Activity is equivalent to Form in desktop environment.
Examples:
start, pause,
stop, restart
playback.
   
Each
view controls
a particular
rectangular
space within the window.
  Views are
activity’s
interaction
with the userprocess.
takes place.
  Services
runwhere
in thethe
main
thread
of the application
Application Components
  ContentView
is the root
view components.
object in the hierarchy of views.
 
It is not a sub thread
of other
  University
Activity.setContentView() method.
Kettering
Kettering University
  Activity is equivalent to Form in desktop environment.
Kettering University
Kettering University
Services
14
  No visual interface.
  Runs in the background of an indefinite period of time.
  Examples:
  Play background music, fetch data over the network.
  Each service extends the Service base class
  It is possible to connect to an ongoing service (and start the service
if it is not already running).
  You can communicate with service through an interface that the service
exposes.
  Examples: start, pause, stop, restart playback.
  Services run in the main thread of the application process.
  It is not a sub thread of other components.
Kettering University
Broadcast Receivers
  A Broadcast Receiver receives and reacts to broadcast
announcements.
Services
15
14
  Broadcast examples from the system
  The timezone change, the battery is low, a picture has been taken, and
  Noetc.
visual interface.
 
application
can haveofany
receivers
to respond to
  An
Runs
in the background
an number
indefiniteofperiod
of time.
any announcements.
  Examples:
  BRs
dobackground
not displaymusic,
user interface.
  Play
fetch data over the network.
  BRs
can
start an
activity
response base
to theclass
information they receive.
Each
service
extends
theinService
  It is possible to connect to an ongoing service (and start the service
if it is not already running).
  You can communicate with service through an interface that the service
exposes.
  Examples: start, pause, stop, restart playback.
Kettering University
  Intent Object
  An abstract description of an operation to be performed.
Intents
  Android system finds the appropriate activity, service, or set of
16
broadcast receivers to respond to the intent.
Intents Object and Intent Filters
17
An inter-app message passing framework
  Two groups of intents
  Activities, Services, Broadcast Receivers are activated by Intents, asynchronous
  Explicit intents:
messages.
  They name the target component.
  can
Component
names
are not
known to developers
of other
apps.
  You
broadcast
messages
system-wide
or to a target
Activity
or Service.
  So they are used for application internal messages.
  Then,
the system
  Implicit
intents: will determine the target(s) that will perform any actions as
appropriate.
  They are often used to activate components in other apps.
  Separate methods for activating each type of component.
  For implicit intents
  Activity: Context.startActivty() or Activity.startActivityForResult()
  Need to test the intent object against Intents Filters associated with
  potential
The responding
activity can look at the initial intent that caused it to be launched by
target.
calling getIntent().
  Service: Context.startService()
Kettering
  University
Android calls the service’s onStart() method and passes it the intent object.
  Broadcast: Context.sendBroadcast(), Context.sendOrderedBroadcast(), …
  Android delivers the intent to all interested receivers by calling their onReceive()
Kettering University
Intent Objects
  Intent Object
  An abstract description of an operation to be performed.
  Android system finds the appropriate activity, service, or set of
broadcast receivers to respond to the intent.
  Two groups of intents
  Explicit intents:
  They name the target component.
  Component names are not known to developers of other apps.
  So they are used for application internal messages.
  Implicit intents:
  They are often used to activate components in other apps.
  For implicit intents
  Need to test the intent object against Intents Filters associated with
potential target.
Kettering University
18
Intent Filters
19
A bundle of information
  Intent Objects contains information of component that receives the intent and the
Android system
Intents Object and Intent Filters
  Intent Objects contains
 
 
 
17
  Component name - optional
  Action
  A string naming the action to be performed.
  Examples
Intent
Object
ACTION_CALL:
Initiate aof
phone
call
  An abstract
description
an operation
to be performed.
  ACTION_EDIT: Display data for the user to edit
  ACTION_MAIN:
Start the
up asappropriate
the initial activityactivity,
of a task service, or set of
Android
system finds
  ACTION_BATTERY_LOW:
A WARNINGto
THAT
THEintent.
BATTERIY IS LOW
broadcast
receivers to respond
the
  Data
Two
groups
of intents
  The
URL of the
data to be acted on.
  Explicit
Categoryintents:
 
  They
Examples:
 
name the target component.
CATEGORY_HOME: The activity displays the home screen.
   
Component
names are not known to developers of other apps.
  CATEGORY_LAUNCHER: The activity can be the initial activity and is listed in the top-level
  Soapplication
they are used
for application internal messages.
launcher.
  Implicit intents:
often used to activate components in other apps.
Kettering
  University
They are
  For implicit intents
  Intents should be resolved since implicit intents do not name a
target component.
18
Intent Objects
  Intent filters are generally in the app’s manifest file
A (AndroidManifest.xml)
bundle of information
 
Objects
contains
information
of component
receivesaction
the intent
and the
  Intent
Most
apps
have
a way
to start
fresh. The that
following
and
Android
system
category are default values of an Android project.
  Intent Objects contains
<intent-filter>
  Component name - optional
<action android:name="android.intent.action.MAIN" />
  Action
<category android:name="android.intent.category.LAUNCHER" />
  A string naming the action to be performed.
</intent-filter>
  Examples
  ACTION_CALL: Initiate a phone call
  ACTION_EDIT: Display data for the user to edit
  ACTION_MAIN: Start up as the initial activity of a task
  ACTION_BATTERY_LOW: A WARNING THAT THE BATTERIY IS LOW
  Data
Kettering
  University
The URL of the data to be acted on.
  Category
  Examples:
Note Pad Example
20
Yourcan
program
have
something
  You
shareshould
your data
and
you canlike…
access shared data of other
String number = "tel:810-555-1234”;
apps.
<activity android:name="NotesList" android:label="@string/title_notes_list”>
…
</activity>
<activity android:name="NoteEditor” ...
…
</activity>
<activity android:name="TitleEditor” ...
…
</activity>
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(number));
startActivity(callIntent);
  Apps do not call ContentProver methods directly. Rather they use
a ContentResolver
object
and callfor
itsphone
methods
  Do
not forget to add the
permission
callinstead.
in your App
Manifest XML file.
  ContentProviders are activated when they are targeted by a
uses-permission android:name="android.permission.CALL_PHONE"
request
from a ContentResolvers.
  Each activity has intent-filters. Followings are from NotesList activity.
 
A Simple Dialer
  ContentProvider base class should be extended to implement a
standard set of methods.
  There are three activities: NotesList, NoteEditor, and TitleEditor
 
  A CP makes a specific set of the app’s data available to other
apps.
21
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<action android:name="android.intent.action.EDIT" />
<action android:name="android.intent.action.PICK" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="vnd.android.cursor.dir/vnd.google.note" />
</intent-filter>
Kettering University
  The second intent filter declares that the activity can VIEW, EDIT, PICK
in the data URI.
Kettering University
Content Providers
Kettering University
22
  A CP makes a specific set of the app’s data available to other
apps.
21
A Simple Dialer
  ContentProvider base class should be extended to implement a
standard set of methods.
Shutting down Components
  An activity can be shut down by calling its finish() method.
  A service can be stopped by calling its stopSelf() or
Context.stopService().
  Your
program
have
something
You can
shareshould
your data
and
you canlike…
access shared data of other
String number = "tel:810-555-1234”;
apps.
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(number));
startActivity(callIntent);
  Apps
do not call ContentProver methods directly. Rather they use
a
ContentResolver
object
and callfor
itsphone
methods
  Do not forget to add the
permission
callinstead.
in your App
Manifest XML file.
  ContentProviders are activated when they are targeted by a
uses-permission android:name="android.permission.CALL_PHONE"
request
from a ContentResolvers.
Kettering University
Kettering University
23
<intent-filter . . . >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
App Manifest
24
App Manifest - Intent Filters
25
  IFs declare the capabilities of its parent component.
  What
an activity
orincludes
service a
can
do and
what
types of broadcasts
  Each
Android
project
manifest
file,
AndroidManifest.xml
foraall
apps
(samecan
name).
receiver
handle.
  A structured XML file.
  Action “android.intent.action.MAIN” and category
“android.intent.category.LAUNCHER”
is the
most
common
  The
principal task of it is to inform Android about the
app’s
components.
 
<activity>, <service>, <receiver> elements
combination.
<?xml version="1.0" encoding="utf-8"?>
  Note: application launcher: the screen listing apps where users can
<manifest . . . >
launch
an app.
<application . . . >
<activity android:name=”edu.kettering.project.FreneticActivity"
  The activity is theandroid:icon="@drawable/small_pic.png"
entry point for the app.
android:label="@string/freneticLabel"
Kettering University
. . . >
</activity>
. . .
</application>
</manifest>
<intent-filter . . . >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
Activity, Tasks, and Processes
  IFs declare the capabilities of its parent component.
  What an activity or service can do and what types of broadcasts a
receiver can handle.
  Action “android.intent.action.MAIN” and category
“android.intent.category.LAUNCHER” is the most common
combination.
Kettering University
  Note: application launcher: the screen listing apps where users can
launch an app.
  The activity is the entry point for the app.
Kettering University
Kettering University
26
Activities, Tasks, and Processes
  One activity can start another including one in a different app.
  Example:
  Your activity needs to display a street map.
  Assuming there is an activity that can do this.
  You activity put together an Intent object and pass it to
startActivity().
Activity, Tasks, and Processes
  Definitions
  Activity
  The… Android ‘Activity’
  Task
  A stack of activities
  Process
  A standard Linux
process and Processes
Activity,
Tasks,
Kettering University
Kettering University
27
26
.apk Package
.apk Package
Activities,
Tasks, and Processes
Process
Activity
Task
Process
.apk Package
Content Provider
.apk Package
Content Provider
Process
Activity
Activities, Tasks, and Processes
.apk Package
.apk Package
Process
Process
ProcessActivity
Service
Activity
Task
Process
Activity
Activity
Service
Content Provider
Content Provider
Content Provider
Content Provider
Process
Kettering University
29
Activity
Activity
Activity
28
Service
Process
Service
Service
Kettering University
Service
Kettering University
30
Process and Thread
Android Activity Lifecycle
31
  An activity has three states:
  Application components are Linux processes.
29a
  When the first of an app’s components needs to be run, Android starts
Activities,
and
Processes
Linux process forTasks,
it with a single
thread
of execution.
  Active, or running:
Process
Thread
  When it is and
in the foreground
of the screen.
30
  Paused:
  Process
  When it lost focus but is still visible to the user.
  It is controlled by the Manifest file.
  Application
  Stopped: components are Linux processes.
  Thread
.apk Package
.apk Package
  User interface
should
always
be
quick
to
respond
Processto user actions.
Process
Task
  Anything that may not be completed quickly should be assigned to a
different Activity
thread.
Activity
Activity
  Threads are created in code using standard Java Thread objects.
  Android also provides many convenient classes
forProvider
managing threads.
Content
Content Provider
Process
Kettering University
Service
Service
   
When
the
first
of an app’s
components
needsactivity.
to be run, Android starts a
When
it is
completely
obscured
by another
Linux process for it with a single thread of execution.
  It still remains all state and member information.
  It may be killed by the system when memory is needed elsewhere.
  Process
  It is controlled by the Manifest file.
  Note: When an activity is paused or stopped, the system can drop it
from memory or simply kill its process.
  Thread
  User interface should always be quick to respond to user actions.
  Anything that may not be completed quickly should be assigned to a
different thread.
Kettering University
  Threads are created in code using standard Java Thread objects.
Android Activity Lifecycle
32
  Since the system can shut down an activity, the user may expect to
return to the activity and find it in its previous state.
33
Android Activity Lifecycle
  onSaveInstanceState()
  Android calls this method before making the activity to being destroyed.
  onRestoreInstanceState()
  Entire life time of an activity
void onCreate(Bundle savedInstanceState)
void onStart()
  Android calls onRestoreInstanceState()
after calling onStart().
void onRestart()
  onCreate() – onDestrory()
void onResume()
  Note that these two methods are
not
lifecycle methods.
void
onPause()
  Visible life time
void onStop()
  They are not called in a proper lifecycle step.
void onDestroy()
  onStart() – onStop()
  You cannot rely on these methods to save some persistent data.
  Foreground life time
  onResume() – onPause()
Kettering University
Kettering University
Kettering University
Android Activity Lifecycle
34
35
Saving Activity State
  Since the system can shut down an activity, the user may expect to
return to the activity and find it in its previous state.
33
Android Activity Lifecycle
  onSaveInstanceState()
  Android calls this method before making the activity to being destroyed.
  onRestoreInstanceState()
  Entire life time of an activity
void onCreate(Bundle savedInstanceState)
void onStart()
  Android calls onRestoreInstanceState()
after calling onStart().
void onRestart()
  onCreate() – onDestrory()
Application Resources
void onResume()
  Note that these two methods are
not
lifecycle methods.
void
onPause()
  Visible life time
void onStop()
  They are not called in a proper lifecycle step.
void onDestroy()
  onStart() – onStop()
  You cannot rely on these methods to save some persistent data.
  Foreground life time
  onResume() – onPause()
Kettering University
Kettering University
  Place resources in a specific subdirectory of your project’s res/
directory.
36
Resource Externalization
  Resource directories supported inside project res/ directory.
Directory
  To specify configuration-specific alternatives for a set of resources:
  Create a new directory in res/ named in the form <resources_name>-<config_qualifier>.
  <resources_name> Resource
is the directory name ofTypes
the corresponding default resources.
Grouping
  <qualifier> is a name that specifies an individual configuration for which these resources.
  You can append more than one <qualifier>. Separate each one with a dash.
  Save the respective alternative resources in this new directory. The resource files must be
named
exactly the in
same
as the default
resource files.of your project’s res/
  Place
resources
a specific
subdirectory
Type
  Externalizing
resources
such
as animation
images and strings
anim/
Define
tween
directory.
  color/
You can maintain Define
them separately
your actual code.
a state list from
of colors
  For example, here are some default and alternative resources:
  drawable/
This allows you to provide
alternative
resources
Bitmap files
or XML files
that that support different
languages, different screen sizes.
layout/
Define user interface layout
  This is extremely important because Android-powered devices become
menu/
Optionsconfigurations.
Menu, Context Menu, or Sub Menu
available with different
  Resource directories supported inside project res/ directory.
raw/
Arbitrary files to save in their raw form
values/
Strings, integers, colors
xml/
Arbitrary XML files
Kettering University
res/
drawable/
icon.png
Directory
Type
layout/
Define user interface layout
background.png
anim/
Define tween animation
drawable-hdpi/
color/ icon.png
Define a state list of colors
background.png
drawable/
Bitmap files or XML files that
Kettering University
menu/
Options Menu, Context Menu, or Sub Menu
raw/
Arbitrary files to save in their raw form
values/
Strings, integers, colors
xml/
Arbitrary XML files
Kettering University
Kettering University
Providing Alternative Resources
37
38
Creating Resources
39
Simple Values
  To specify configuration-specific alternatives for a set of resources:
  Create a new directory in res/ named in the form <resources_name>-<config_qualifier>.
 
 
 
 
<resources_name> is the directory name of the corresponding default resources.
<qualifier> is a name that specifies an individual configuration for which these resources.
You can append more than one <qualifier>. Separate each one with a dash.
Save the respective alternative resources in this new directory. The resource files must be
named exactly the same as the default resource files.
  String
  <string name=“your_name”>Kettering</string>
Providing Alternative Resources
  Color
 
  For example, here are some default and alternative resources:
res/
drawable/
icon.png
background.png
drawable-hdpi/
icon.png
background.png
Kettering University
38
  <color name=“transparent_blue”>#770000FF</color>
  Format
  #RGB
#RRGGBB
To specify
configuration-specific alternatives for a set of resources:
  #ARGB
  Create a new directory in res/ named in the form <resources_name>-<config_qualifier>.
  #AARRGGBB
  <resources_name> is the directory name of the corresponding default resources.
  Dimensions
  <qualifier> is a name that specifies an individual configuration for which these resources.
 
  <dime name=“border”>5dp</dimen>
  You can append more than one <qualifier>. Separate each one with a dash.
  Scale identifier
   
Save
the respective alternative resources in this new directory. The resource files must be
px (screen pixels)
named exactly the same as the default resource files.
  in (physical inches)
  pt (physical points)
For example, here are some default and alternative resources:
  mm (physical millimeters)
res/
  dp (density independent pixels relative to a 160-dpi screen)
drawable/
  sp
(scale independent pixels)
icon.png
Kettering University
background.png
drawable-hdpi/
  Create different bitmaps
 
 
 
 
xhdpi: 2.0
hdpi: 1.5
mdpi: 1.0 (baseline)
ldpi: 0.75
Supporting Different Screens
40
  This means that if you generate a 200x200 image for xhdpi devices, you should
  Four
general
categorized
generate
the same
resource indevice
150x150 screens:
for hdpi, 100x100 for mdpi, and 75x75 for
ldpi
devices.
 
Sizes:
small, normal, large, xlarge
  Densities:
low(ldpi),
medium
(mdpi),
high(hdpi),
extra high (xhdpi).
  Then
place the
files in the
appropriate
drawable
directories
MyProject/   Create
different layouts
res/  
 
 
 
xhdpi: 2.0
hdpi: 1.5
mdpi: 1.0 (baseline)
ldpi: 0.75
MyProject/ res/ drawable-‐xhdpi/ awesomeimage.png drawable-‐hdpi/ awesomeimage.png drawable-‐mdpi/ awesomeimage.png drawable-‐ldpi/ awesomeimage.png Kettering University
Kettering University
42
  Drawable
41
  Drawable resources include bitmaps and NinePatch (stretchable PNG)
Supporting
Different Screens
images.
  Layouts
  Layout
resources
let you decouple your app’s presentation layer.
  Create
different
bitmaps
xhdpi: 2.0 user interfaces in XML rather than constructing them in code.
   
Designing
  hdpi: 1.5
  mdpi: 1.0 (baseline)
  ldpi: 0.75
  This means that if you generate a 200x200 image for xhdpi devices, you should
generate the same resource in 150x150 for hdpi, 100x100 for mdpi, and 75x75 for
ldpi devices.
MyProject/ res/ drawable-‐xhdpi/ Kettering
University
awesomeimage.png drawable-‐hdpi/   Create different bitmaps
  Then place the files in the appropriate drawable directories
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); }   Then place the files in the appropriate drawable directories
41
  This means that if you generate a 200x200 image for xhdpi devices, you should
generate the same resource in 150x150 for hdpi, 100x100 for mdpi, and 75x75 for
ldpi devices.
  drawable-‐xhdpi/ MyProject/
awesomeimage.png res/
drawable-‐hdpi/ layout/
awesomeimage.png main.xml
drawable-‐mdpi/ layout-large/
awesomeimage.png main.xml"
drawable-‐ldpi/ awesomeimage.png   Simply
Kettering
Universityreference the layout file in your app as usual.
Creating Resources
Supporting Different Screens
Accessing Resources
43
  You can refer a resource via its ID.
  R class
Creating
  All resource IDs Resources
are defined in your project’s R class.
42
  The R class is automatically generated by the aapt tool.
  Resource ID
  Drawable
  A resource ID has a unique name and is composed of:
Resourceresources
type:
   
Drawable
include bitmaps and NinePatch (stretchable PNG)
  string, drawable, layout, etc.
images.
  Resouce name:
  Layouts
  Either the filename (excluding the extension) or the value in the XML
android.name attribute, if the resource is a simple value such as a string,
  Layout
resources let you decouple your app’s presentation layer.
a color.
  Designing user interfaces in XML rather than constructing them in code.
  Accessing a resouce: string is a resource type. hello is a resource name
  In code: R.string.hello
  In XML: @string/hello
Kettering University
Layout Definition
44
  When you compile your source code, each XML layout file is
compiled into a View resource.
XML for Resource
  You should load it in your Activity.onCreate().
  Layout is an architecture about user interfaces in an Activity
  XML file: res/layout/*.xml
  Only
one
element
that should
Viewcan
or abe
ViewGroup.
  If the
xmlroot
file name
is main.xml,
thenbe
thealayout
accessed by
  Two ways of definition of layouts
  Add child elements to the root view.
R.layout.main in your source code.
  XML
  Use resource editor to make layout.
  ADT provides the preview of an XML file.
  The best way is to make a layout is using both the XML editor and the
XML graphical editor.
  In code
  Create Views and ViewGroups in runtime.
Kettering University
XML Resource Load
  When you compile your source code, each XML layout file is
compiled into a View resource.
XML for Resource
  You should load it in your Activity.onCreate().
  XML file: res/layout/*.xml
  Only
one
element
that should
Viewcan
or abe
ViewGroup.
  If the
xmlroot
file name
is main.xml,
thenbe
thealayout
accessed by
R.layout.main in your source code.
  Add child elements to the root view.
<?xml version="1.0" encoding="utf-8"?>
public void
onCreate(Bundle savedInstanceState) {
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
super.onCreate(savedInstanceState);
android:layout_height="fill_parent"
setContentView(R.layout.main);
android:orientation="vertical" >
}
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a TextView" />
<Button android:id="@+id/button"
Kettering University
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a Button" />
45
<?xml version="1.0" encoding="utf-8"?>
public void
onCreate(Bundle savedInstanceState) {
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
super.onCreate(savedInstanceState);
android:layout_height="fill_parent"
setContentView(R.layout.main);
android:orientation="vertical" >
}
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a TextView" />
<Button android:id="@+id/button"
Kettering University
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a Button" />
</LinearLayout>
Kettering University
46
ID of Element
  Any View object has a unique ID.
45
  In your XML code, the ID is defined with a string.
  android:id=“@+id/myButton”
  @ indicates the rest of the string should be identified as an ID resource.
  + means adding new resource name.
  In your source code, the ID can be referred by an integer.
  Button myButton = (Button)findViewById(R.id.myButton);
  Example:
In XML …
<Button android:id="@+id/myButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/my_button_text"/>
In source code …
Button myButton = (Button) findViewById(R.id.myButton);
Kettering University
47
48
Questions?
Kettering University