7/28/2019 Writing Android Apps
1/88
Introductions
I know this is a little lame but...
Who am I?
Who are you guys?
What kind of programming experience do you
have?
Any experience with Android / mobile app
development?
What are you hoping to get out of the course?
7/28/2019 Writing Android Apps
2/88
Android Architecture
7/28/2019 Writing Android Apps
3/88
Android Architecture Layers
Applications
Fairly self explanatory, this upper layer is where the
applications themselves live Application Framework
Set of services and systems available to all
application Views: used to build applications includes: lists, grids,
text boxes, buttons, and more
Content Providers: allow access to data from other
applications, and to share own data
7/28/2019 Writing Android Apps
4/88
Android Architecture Layers
Resource Manager: access to non-code resources, like
images and layout files
Notification Manager: lets applications display custom
alerts Activity Manager: application lifecycle management
and stack navigation
Libraries
System C Library standard linux style system C
library
Media Libraries based on OpenCORE supports,
MPEG4, H.264, MP3, AAC, AMR, JPG, and PNG
formats among some others
7/28/2019 Writing Android Apps
5/88
Application Architecture Layers
Surface Manager manages the display
LibWebCore modern web browser engine supports
Android browser and web views
SGL 2D graphics engine
3D libraries based on Open GL 1.0 APIs
FreeType font rendering library
SQLite database engine
Android Runtime
Set of core libraries that contains most of the
functionalities of core Java libraries
Applications all run in a Dalvik Virtual Machine
7/28/2019 Writing Android Apps
6/88
Android Architecture Layers
Linux Kernel
Linux 2.6 Kernel
Manages interaction between hardware andthe rest of the software stack
Provides memory management, process
management, network stack, and driver
model services
7/28/2019 Writing Android Apps
7/88
Where do we start?
Android App Inventor
From google, you will need to signup for a gmail
account to access this, however no additionalapplication or signup is necessary anymore.
You will need to go to
http://appinventor.googlelabs.com/learn/setup/
Follow the instruction to configure your computer.
http://appinventor.googlelabs.com/learn/setup/http://appinventor.googlelabs.com/learn/setup/7/28/2019 Writing Android Apps
8/88
Google App Inventor
This is the app inventor palette,
and will appear on the left side
of the screen You drag and drop elements from
here to add them to the canvas
Click on the question marks to goto a description of that element
7/28/2019 Writing Android Apps
9/88
Google App Inventor
This is the viewer,
or canvas.
It shows whatyou'll see on the
screen
You arrange your
elements here At the bottom are
non-visible
components
7/28/2019 Writing Android Apps
10/88
Google App Inventor
This is the components pane, here
you can see the things you have
added to your view You can rename and delete
components using the buttons
near the bottom
If you have added any media they
will appear in the media section
below this pane
7/28/2019 Writing Android Apps
11/88
Google App Inventor
This is the properties tab,
here you can set default
values for your components Also allows you to set height
and width
Settings in here will be theinitial settings when the
component loads but may
be changed later
7/28/2019 Writing Android Apps
12/88
Google App Inventor
This is the block
editor where we
will put together
the code for an
app inventor
project
There are built-in
functionalities
and we can addour own either
based on the
components we
added or
functions we need
to create
7/28/2019 Writing Android Apps
13/88
Android SDK Basics
The Building Blocks of Android
Dalvik VM (Dalvik is a town in Iceland)
Designed to address performance issues of handheld
environment Traditional Java virtual machines include all the libraries
used to build each application
Android Libraries could be 10-20MB or more
The Dalvik VM reuses parts of the various libraries toreduce the size by half or more (.jar vs .dex)
It does not at this time implement Just-In-Time compilation
7/28/2019 Writing Android Apps
14/88
Android SDK Basics
Dalvik VM continued
Reduced instruction set
Attempting to reduce instruction set by nearly 30 percent
Performance speed increase due to this particulary
important for handheld devices as we expect very
responsive performance
Because of this applications run in Dalvik VM byte
code
This means you cannot execute Java byte code in android,
despite java being the language it is built on
You must convert Java code to .dex Dalvik VM files
7/28/2019 Writing Android Apps
15/88
Android SDK Basics
Android Software Stack
We covered this pretty well back in lecture one
Important to remember that there are two layers of libraries
we work with Java SDK
Native C/C++ libraries
These are combined in the Dalvik VM, check your book
for more details on the specific APIs
Android Emulator
Limitations: USB connections, Camera, Video,
Headphones, Battery, Bluetooth
7/28/2019 Writing Android Apps
16/88
Android SDK Basics
The Android UI
Fourth Generation UI like JavaFX or Microsoft
Silverlight.
Interfaces (called Views) are declared in XML files
(these are our building blocks)
These can be grouped into View Groups
A full screen or menu is called an Activity and it made
up of multiple views and view groups
Lifecycle of the application works at activity level
(start, stop, pause, resume, etc.)
7/28/2019 Writing Android Apps
17/88
Android SDK Basics
Android Foundation Components
Intents
A combination of ideas intended to achieve an action
It is basically a passive data structure containing informationon the action to be performed
2 main parts: action and data
Resources
Accessed through the R class
Can be used for simple strings or files, but also for XMLbased views and more
I.D.s are autogenerated and facilitate easy access and use of
resources
7/28/2019 Writing Android Apps
18/88
Android SDK Basics
Content Provider
Abstract wrapper for data sources to make them appear
to be a consumer and emitter of RESTful services
RESTful Representational State Transfer Focuses on using the http verbs and URIs to manage
web services, more on this as we move on
Somewhat interesting as Google uses SOAP (Simple
Object Access Protocol) for almost all of their web
services
For some more info on android packages and
components see Ch 1. in your book
7/28/2019 Writing Android Apps
19/88
Making an Android Application
The main parts of an Android Application
View as covered before these are our user interface
elements
Includes: Buttons, Labels, Textfields, etc.
Knows how to draw itself (Fourth Generation)
Activity group of views usually representing a single
screen This is a UI concept
Can be viewless under some circumstances
7/28/2019 Writing Android Apps
20/88
Making an Android Application
Intent defines a generic structure to do some work
Uses: broadcast a message, start a service, launch activity,
display web page, dial a number
May be initiated by your application or from a separate
application
Content Provider and Services these provide access to
resources and functions
AndroidManifest.xml important file similar to web.xml
in J2EE
Lists applications activities, services, and permissions
7/28/2019 Writing Android Apps
21/88
Your First Application
Let's look at how these parts come together when
you make an app
Open up Eclipse New Project Android Project
You should see a form to create a new project
Give your project a name, let it create a new project
in the workspace, and select an Android Version
(2.1 or 2.2 will usually be best)
7/28/2019 Writing Android Apps
22/88
Your First Application
Application name will appear at the top of your application
Package name should be the initial package to create
Create Activity will create an initial activity (UI Screen)
Min SDK Version should be set to match your android version
Fill this out: Package = com.helloclass Activity = HelloActivity
7/28/2019 Writing Android Apps
23/88
Your First Activity
Click Finish this will build an application skeleton
based on your settings
Now we move on to working on the application Expand the app folder, src folder, and package, till you
get to the .java file
Open that up and take a look
You should see a class implementation and the OnCreate
function
Notice how things are broken out in the package explorer
7/28/2019 Writing Android Apps
24/88
A bit on event driven design
Much like the work we did on the app inventor, regular
Android apps are event driven
Given the graphical nature and interface restrictions ofmobile apps this is necessary
OnCreate is an event triggered whenever the activity is
created, it's a lifecycle event and not something we
call Much of what we will be working with will work like
this as we move forward
7/28/2019 Writing Android Apps
25/88
Your First Activity
Let's look at what we have here
super.onCreate(savedInstanceState) This will call the base activity
onCreate method and load any savedstate information setContentView(R.layout.main)
This will load the views for theactivity
It will get the information from theresources (res), layout group,main.xml file
7/28/2019 Writing Android Apps
26/88
Your First Acticity
Adding a text view
Add 2 lines after super.onCreate
TextView tv = new TextView(this); tv.setText(Hello World!);
Eclispse should add the include for
android.widget.TextView
Since we are not adding this properly through an xml filewe need to get change the setContentView line
setContentView(tv);
7/28/2019 Writing Android Apps
27/88
Your First Activity
Now run your application
Eclipse should ask you about what you want it to
run as, select android application You will also need to let ADT create an emulator to
run it in
You can look to Ch. 2 of our book for some moreinstruction on run configurations
Now we will take a look at the application structure
7/28/2019 Writing Android Apps
28/88
Examining an App
For now we are just going to take a look at the res
resource folder
Underneath the top layer res folder you will see
several others, you can add more here as needed and
create even deeper levels
These are accessed with the R resource class
R...filename
You could see this in our early app
setContentView(R.layout.main)
7/28/2019 Writing Android Apps
29/88
Working with an XML layout
Open up Layout main.xml
This will open a area for you to do the layout
graphically In the bottom of that window you should see a main.xml
tab, click that to see the code view
You'll see we already have a text view element in there,
lets see what thats all about
Go back into you app and change the code
7/28/2019 Writing Android Apps
30/88
Resources
Generated and accessed through the R.java class
Usually they are defined by an xml file with two
exceptions Raw resources: video, sound, etc.
Assets: these resources do not get generated id's
and are not compiled
Can be an entire file (main.xml layout) or
values from a file (strings.xml)
7/28/2019 Writing Android Apps
31/88
Resources
Why use resources like this?
Values are not hard coded in, meaning they can
be changed without recompiling and
redeploying
One point of reference, changing the resource
changes that value everywhere it is used
Imagine the marketing department decides on afont change, you change the setting on your
string resources and you are all done
7/28/2019 Writing Android Apps
32/88
Resource Types Overview
Strings several forms of strings
Layouts used to build an UI screen
Colors Identifiers for hex color codes
Dimensions size information for elements
Images images, .jpg .gif .png and so on
Drawable many options, colored shapes
XML arbitrary xml file, must be parsed
Raw raw data, non-compiled binary or text
Assets arbitrary non-compiled files, no ids
7/28/2019 Writing Android Apps
33/88
Strings
Can hold values with plain strings, java formatted
strings, and even html tagged strings (mostly supports
formatting tags)
IDs accessed through R.string.
XML node is formed by /resources/string
My String
Can have many strings in one file in /res/values
7/28/2019 Writing Android Apps
34/88
Strings
Access via the activity getString method
activity.getString(R.string.mystring);
Or do this in the layout
To use a Java String
Hello %1$s String myJavaString = activity.getString
(R.string.javastring);
MyJavaString = String.format(myJavaString, World!)
7/28/2019 Writing Android Apps
35/88
Strings
To use an html string
This is slanted, this is
bold
String htmlString = activity.getString(R.string.htmlString)
Spanned mytextspan = android.text.Html.fromHtml(htmlString)
textview.setText(mytextspan)
Or
7/28/2019 Writing Android Apps
36/88
Colors
Color value using one of the following Alpha-Red-
Green-Blue formats
#RGB
#ARGB
#RRGGBB
#AARRGGBB
Accessed through R.color. Many values per file (like string) in /res/values
Node structure /resources/color
7/28/2019 Writing Android Apps
37/88
Colors
To use a color
#FF0000
int mycolor =activity.getResources().getColor(R.color.red);
or
7/28/2019 Writing Android Apps
38/88
Dimensions
Stores dimension information that you use to style your
UIs and change without changing the code
Dimensions may be specified in px Pixels
in Inches
mm: Millimeters
pt: Points
dp: Density-independent pixels (based on 160 dpi)
sp: Scale-independent pixels
7/28/2019 Writing Android Apps
39/88
Dimensions
Accessed by R.dimen.
Many per file stored in /res/values
Node Structure /resources/dimen Usage example
2px
float dimen = activity.getResources().getDimension(R.dimen.mydimen)
or
7/28/2019 Writing Android Apps
40/88
Image
Generates IDs for image file resources, supported types
include
jpg
gif
png
ID will be the filename minus the extension
Accessed with R.drawable.
Each image file is placed seperately in /res/drawable
7/28/2019 Writing Android Apps
41/88
Image
No node structure as these are not XML
Usage examples
I recommend the above method but you could...
BitmapDrawable image =
activity.getResources().getDrawable(R.drawable.);
Button.setBackgroundDrawable(image); or
Button.setBackgroundResource(R.drawable.image);
7/28/2019 Writing Android Apps
42/88
Shape-Drawable
These are colored shapes that can be used like images,
there are four different shapes. Called a Color-
Drawable in our book
rectangle
oval
line
ring See the book for how to make a Color-Drawable.
Shape is now a documented resource so we will use
that.
Sh bl
7/28/2019 Writing Android Apps
43/88
Shape-Drawable
Accessed through R.drawable.
One XML file per shape, you can set the nodes
you'll set the shape in here set the padding like an html block
used to create rounded rectangle
set a color gradient
set the size
solid color instead of the gradient
see android documentation for all the available options
Sh D bl
7/28/2019 Writing Android Apps
44/88
Shape-Drawable
Example file:
Sh D bl
7/28/2019 Writing Android Apps
45/88
Shape-Drawable
To implement
I recommend the above but just in case...
GradientDrawable myRect =
(GradientDrawable)activity.getResources().getDrawable(R.
drawable.filename)
textView.setBackground(myRect)
A bit XML
7/28/2019 Writing Android Apps
46/88
Arbitrary XML
Allows you to work with any old XML file,
providing quick reference, localized resource,
compiled and stored efficiently
Stored in /res/xml as individual files
Referenced via R.xml. no extension
You need to use the XmlPullParser to parse the file.
A bit XML
7/28/2019 Writing Android Apps
47/88
Arbitrary XML
Assume we have the XML file test.xml
Hello World, this is parsed XML data
Get a parser XmlResourceParser xmlparser =
activity.getResources().getXml(R.xml.test);
A bit XML
7/28/2019 Writing Android Apps
48/88
Arbitrary XML
Now to parse the file:
StringBuffer sb = new StringBuffer();
xpp.next();
int eventType = xpp.getEventType();
while (eventType ! = XmlPullParser.END_DOCUMENT)
{
if(eventType == XmlPullParser. START_DOCUMENT) {
sb. append(" ******Start document") ;
}
Arbitrar XML
7/28/2019 Writing Android Apps
49/88
Arbitrary XML
else if(eventType == XmlPullParser.START_TAG)
{
sb. append(" \nStart tag "+xpp. getName()) ;
}
else if(eventType == XmlPullParser.END_TAG)
{
sb. append(" \nEnd tag "+xpp. getName()) ;
}
else iff(eventType == XmlPullParser.TEXT)
{
Arbitrary XML
7/28/2019 Writing Android Apps
50/88
Arbitrary XML
sb. append(" \nText " +xpp.getText() );
}
eventType = xpp. next() ;
}//eof-while
sb.append("\n******End document" );
the string buffer can now be sent to a TextView or
wherever the data is needed
Raw Resources
7/28/2019 Writing Android Apps
51/88
Raw Resources
Allows you to store raw uncompiled binary or text
files. They are given an ID for R.java though.
Accessed via R.raw.
These is no node structure as these are individual files
not XML
You will need to use a java InputStream to process the
file, look into java documentation for more info on
InputStream
Assets
7/28/2019 Writing Android Apps
52/88
Assets
You can create your own directory structure
under /assets to keep whatever files you like
Not part of the /res directories Does not generate IDs for R.java
You must specify the relative path to the file
starting at /assets (do note include /assets) Use the AssetManager class to access them
Assets
7/28/2019 Writing Android Apps
53/88
Assets
Usage example
assume that we have /assets/test.txt
AssetManager am = activity.getAssets() ; InputStream is = am.open(" test.txt") ;
do something
is.close() ; very similar to raw resources
Directory Structure Reference
7/28/2019 Writing Android Apps
54/88
Directory Structure Reference
/res/values/strings. xml or /colors.xml or /dimens.xml or /attrs. xml or
/styles.xml
/res/drawable/*. png or /*. jpg or /*. gif or /*. 9. png
/res/anim/*. xml /res/layout/*. xml
/res/raw/*.*
/res/xml/*.xml
/assets/*. */*. *
Note the anim directory, we aren't really covering that at the moment,
you can look up Animation Resources in the Android documentation
Content Providers
7/28/2019 Writing Android Apps
55/88
Content Providers
What are they?
Create a wrapper around data (encapsulation)
Allow us to expose, or access, an applications data Only needed for external access
Usually based around an SQLite database
Android has built in providers and you can write
your own custom content provider
Content Providers
7/28/2019 Writing Android Apps
56/88
Content Providers
How can we get a look at one of the databases:
In your Android SDK directory find \platform-tools
run \platform-tools\adb.exe shell to get shell accessto the device
you can see built in providers under /data/data
Custom providers will also place their databases in
here
You can access the database with sqlite3
Content Providers
7/28/2019 Writing Android Apps
57/88
Content Providers
How do they work:
Content Providers combine elements of many other
concepts out there like: web sites, web services,
RESTful operations, and stored procedures.
Like a website each content provider has is registered
with a uri string (like a url) called an authority
The authority is unique and will base of a set of URIsthat will expose what the content provider offers
7/28/2019 Writing Android Apps
58/88
A content provider uri may look like:
content://edu.iit.itm555.provider.students/ content://edu.iit.itm555.StudentProvider/Students
content://edu.iit.itm555.StudentProvider/Student/1 content:///path-segment1/path-segment2...
How to register authority in AndroidManifest.xml
much like services in .NET
android:name the provider class name
android:authorities the uri used to access the content provider
Content Provider
7/28/2019 Writing Android Apps
59/88
Content Provider
The content provider should then provide operationsthrough
content://com.my-company.MyProvider/
Many android internal services are not fully qualified, so maybe accessed through shortened uri, such as content://contacts/
Through these URIs content providers expose data like a
service
The caller in this case is expected to know the columns androws structure of the data and no special help with that is
passed along
Content Providers
7/28/2019 Writing Android Apps
60/88
Content Providers
In order to provide proper access to these columns
the provider should implement an interface or
group of constants providing the column names
We'll see some of this in our first example app.
A MIME type will be included to indicate the type
of data the URI is providing
Retrieving this MIME type can help you decide
how to handle the data
Content Providers
7/28/2019 Writing Android Apps
61/88
Content Providers
MIME type specifications have two parts, a type and
sub type
text/html
text/xml
text/css
application/pdf
application/vnd.msexcel
http: //www.iana.org/assignments/media-types/
Content Providers
7/28/2019 Writing Android Apps
62/88
Content Providers
Android uses the vnd type and subtypes to indicate
vendor specific non-standard types
Android also has two MIME type forms
single: vnd.android.cursor.item/vnd.name.contenttype
collection: vnd.android.cursor.dir/vnd.name.contenttype
When creating MIME types type and subtype need to
be unique for the data they represent You will almost always need the vnd prefix
Namespace them based on your need
Content Providers
7/28/2019 Writing Android Apps
63/88
Let's look at an example of using a built in content provider
First we have to add the access permission in the manifest
This will give us read access to the contacts provider
We import android.provider.ContactsContract, we can look at the
documentation to see what this provides us
ContactsContract.Contacts.CONTENT_URI
ContactsContract.Contacts._ID
ContactContract.DISPLAY_NAME
Content Providers
7/28/2019 Writing Android Apps
64/88
Using a cursor:
A cursor is an object that holds a collection of rows,
accessed one at a time
Make a query to get our cursor (c)
c.moveToFirst the cursor starts before the first record
so we need to move it up
c.getString, c.getInt, etc. providing column names toretrieve the data
You need to know the column name and type
Content Providers
7/28/2019 Writing Android Apps
65/88
c.moveToNext to move to the next record
The cursor can be moved forward or back, and can
provide a row count
Some extra concepts: Projection an array of column names
Learn about built in provider columns by reading the
documentation There are many more cursor methods, see the
documentation
Content Providers
7/28/2019 Writing Android Apps
66/88
How to refine our data:
Using a where clause
Passed through the uri
content:///notes/2
Explicit where in our query
managedQuery(Uri uri, String[ ] projection, String
selection, String[ ] selectionArgs, String sortOrder)
Make selection and selectionArgs non null
Content Provider
7/28/2019 Writing Android Apps
67/88
Inserting Data (updates and deletes are similar)
ContentValues
key/value pair dictionary used to hold values for a single
record These are like a column name/vaue setup
We make this first for any record we want to add
Content Resolver
Used to insert the record
We are not making a direct database insert
Uri uri = contentResolver. insert(CONTENT_URI, values);
Content Provider
7/28/2019 Writing Android Apps
68/88
Making a custom content provider
Extend the ContentProvider class
Implement the required methods
query
insert
update
delete
getType
Register the provider
Content Provider
7/28/2019 Writing Android Apps
69/88
You will also need to set up a database, and you
should create a class or interface to provide
constants for all the database metadata
We'll look at all of these things in our example of a
custom content provider.
After we set up our custom content provider, we'll
look at accessing it both from the local app andfrom a seperate app.
Intents
7/28/2019 Writing Android Apps
70/88
What are intents for:
Can invoke other application from your app
Can invoke internal and external components of your
application
Can raise events
Intents can carry a payload (data) that can affect the
action taken by your application An action with it's associated payload
Intents
7/28/2019 Writing Android Apps
71/88
We have to register these actions so that our app
knows what to do in the manifest
Intents
7/28/2019 Writing Android Apps
72/88
To invoke the intent once registered
public static invokeMyApplication(Activity parentActivity) {
String actionName="com.androidbook.intent.action.ShowBasicView ";
Intent intent = new Intent(actionName);
parentActivity.startActivity(intent)
}
Assuming we had a classpublic class BasicViewActivity extends Activity {
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.some-view);
} }//eof-class
Intents
7/28/2019 Writing Android Apps
73/88
What are some of the built in android intents
ACTION_WEB_SEARCH invoke a web search
(based on payload)
ACTION_DIAL open phone dialer with an enterednumber based on payload
ACTION_CALL call a phone number based on
payload (there seems to be some permission issues with
this) ACTION_VIEW this will largely depend on the
payload, In fact we can override this
Intents
7/28/2019 Writing Android Apps
74/88
Using an intent-filter with a mime type
Lets look at an example.
Also looking at using a menu Finally a class challenge, make a contacts picker
Working with XML layout
7/28/2019 Writing Android Apps
75/88
setContentView(R.layout.main)
Comment out the two text view lines
Run the app again, and look we have some text
If we look in main.xml we see the following
Working with XML layout
7/28/2019 Writing Android Apps
76/88
We see some settings for the text view being displayed
@string/hello what does this do
We are referencing the string value identified as hello
Explore into the values folder instead of layout, open
strings.xml
From here we can see and change the hello string
Layout Managers
7/28/2019 Writing Android Apps
77/88
What are the different types:
LinearLayout: Children are organized either horizontal or
vertical
TableLayout: Organize children in tabular form
RelativeLayout: Organize children relative to one
another or parent
FrameLayout: Allows you to dynamically control layout
AbsoluteLayout: depricated format
Layout Managers
7/28/2019 Writing Android Apps
78/88
Extends the android.widget.ViewGroup class
This means that we can access layout managers by
instanciating them as a ViewGroup
Address sizing and positioning only Weight and Gravity
Weight priority of component sizing
Gravity sets alignment of text or component See example app
Linear Layout
7/28/2019 Writing Android Apps
79/88
This is the manager we are familiar with
Children are added inside the linear layout in the
order we want them to appear
We can use weight and gravity to adjust the exact
appearance a bit, as show in our example
Table Layout
7/28/2019 Writing Android Apps
80/88
Extends LinearLayout and creates a row/column
structure
To create a table layout in xml
Declare the TableLayout just like a LinearLayout
Use to define the row nodes
Each view in the row node will create a column for the
layout Number of columns determined by biggest row
Table Layout
7/28/2019 Writing Android Apps
81/88
Some properties we can set
android:stretchColumns list the columns to stretch
android:shrinkColumns list columns to wrap
content on in order to it better
android:collapseColumns hides listed columns
android:layoutSpan allows you to set a view to
span multiple columns
Relative Layout
7/28/2019 Writing Android Apps
82/88
This layout manager allows you to arrange views
relative to each other
Create the RelativeLayout like our other layouts
In each child element assign the values of layout_below,layout_above, layout_toRightOf, layout_toLeftOf,
layout_alignParentTop, layout_alignParentBottom,
and/or layout_alignParentCenter
These elements can be combined as necessary to createdesired layout
Frame Layout
7/28/2019 Writing Android Apps
83/88
Very simple layout generally used to hold one viewobject that will be swapped in and out
All child objects are attached to the upper left any new
ones will just over write on top of previous ones,unless you hide some
Often used with images, but could be used with other
views
Largest child element determines size
SetConsiderGoneChildrenWhenMeasuring() to make sure
room is left for invisible opponent
Menus
7/28/2019 Writing Android Apps
84/88
Android is very friendly to us in regards to menus
It automatically creates a basic menu and passes it to
onCreateOptionsMenu(Menu)
If that method returns true then a menu will be available We add items using
menu.add(,,,)
menu.add(0,1,0,Item One)
Every item but is optional use MENU.none
Menus
7/28/2019 Writing Android Apps
85/88
Responding to a menu click
onOptionsItemSelected(MenuItem item)
Use a switch(item.getItemId()) to respond based on which item
was clicked Return super.onOptionsItemSelected(item) as the default to
release the menu display
You can also implement
menuItem.setOnMenuItemClickListener(myResponse); to
use a callback function in place of the default
You can also set an intent directly with setIntent()
Menus
7/28/2019 Writing Android Apps
86/88
Other bits about menus
Expanded menus you'll get a more menu item if you
overflow the menu space
Use menuitem.setIcon(drawable) to set a picture for themenu item
You can also create submenus and context menus, you
can find these in your book and we may cover them in
coming classes Menus can be defined through XML
XML Menu
7/28/2019 Writing Android Apps
87/88
To create and use an XML based menu
Define an XML file with node structure
Place that file in /res/menu (R.menu.)
Load the menu by the resource id
Respond to items based on their resource id
XML Menus
7/28/2019 Writing Android Apps
88/88
Example of XML file and how to use it
@Override public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_menu, menu);
return true;
}
http://schemas.android.com/apk/res/androidhttp://schemas.android.com/apk/res/android