Download Tutorial 2 – Information on Android App Terminology and Resources

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Tutorial 2 – Information on Android App Terminology and Resources
GENERAL INFORMATION
~
~
Three main application components of an Android application are the following classes:

Context
The application context is the central location for all top-level application functionality. The app context can be
used to access settings, preferences and resources shared across multiple activities. For example, you might
want to keep track of each user’s name and score.

Activity
An Android app is a collection of tasks, each of which is called an activity; each activity has a unique purpose and
a unique user interface. For example, if your app has a splash screen, menu screen, game screen, help screen
and score screen, every one of these screens (user interfaces) will need a separately defined activity.

Intent
An Intent object encapsulates a task request used by the Android operating system. It can be very specific, like
requesting for a certain activity to be launched. Intents can also be used to pass data (called extras) between
activities. Lastly, intents can be used to call on other applications, like launching a web-browser at a specific
website address.
Other components to consider:

Dialogs
Phone screens are small. Sometimes you want to provide a message to the user without building an entire new
activity. Activity dialogs are ‘pre-designed’ quick user interfaces that don’t take up an entire screen. Some
dialogs beyond the basic one include: AlertDialog, CharacterPickerDialog, DatePickerDialog, ProgressDialog and
TimePickerDialog. You can also custom make a dialog if you want.

Fragments
A fragment is a block of user interface with its own life cycle that can be reused in different activities. E.g. If you
need to show a list of items as well as a details view in both portrait and landscape modes, the list could be a
fragment and the details could be a fragment. Each fragment could be displayed according to the mode (i.e. one
under the other or side by side).
Managing Resources
~
Android applications rely on strings, graphics, and other kinds of resources in order to provide the user with a good
functioning program. Resources fall into two types:

System Resources
These are defined by the Android platform and are accessible to all apps through the Android SDK. They are a
“standardized set of resources that provide users with common styles, useful templates and common strings
and colours. For example, the Android system string resource class contains strings for words like OK, Cancel,
Yes, No, Cut, Copy and Paste. (See http://goo.gl/T1SuP for a complete list.)
System resources are stored within the android.R.package. There are classes for each major type of resource.
Use the static getSystem() method from the Resources class to retrieve system resources, followed by the
specific get method based on the type of resource.
E.g. Suppose you need to retrieve the OK string:
String confirm = Resources. getSystem().getString(android.R.string.ok);
To reference this string in XML code or for a control’s property (i.e. in a layout):
@android:string/ok

Application Resources
Defined by the developer, these are specific to the application. For example, background colour, font type and
size, images, animations, etc. all fall under this category. Application resources are created and stored within
the Android project files under the /res directory. Most common are:
o Strings, colours, and dimensions (sizes)
o Drawable graphics files
o Layout files
o Raw files
Resource types are defined with special XML tags and organized into specially named project directories, like
/drawable, /layout and /values.
Resource files stored within /res must be named according to the following rules:
o Lowercase
o A combination of letters with any: numbers, underscores and periods only
o Unique
o
Resources can be loaded in the Java code, usually from within an activity. They can also be referenced using
XML through XML layouts. Once resources are compiled at build time, their name dictates their variable name:
E.g. Suppose a graphics file is saved within the /drawable subdirectory under the /res subdirectory as mypic.jpg
To reference this graphic in XML code or in the properties window of a control, use @drawable/mypic
Application resources can be accessed programmatically using the generated class file called: R.java. To
reference a resource from within your Activity class, you must retrieve the Resources object and then make a
method call based on the type of resource you want.
E.g. Suppose you need to retrieve a string named greeting that is defined in the strings.xml resource file:
String greet1 = getResources().getString(R.string.greeting);
To reference this string in XML code or for a control’s property (i.e. in a layout):
@string/greeting
For a complete list of resource types in addition to information about their management, go to:
http://developer.android.com/guide/topics/resources/available-resources.html
~ covers animation, color state, drawable, layout, menu, string, style and more
Working with Simple Resource Values
~
Simple resources should be defined in XML files under the /res/values project directory.

Strings
String resources are used wherever your app needs to display text. Strings are defined by the <string> tag and
identified using the name property. They should be stored in /res/values/strings.xml. An example:
<?xml version=“1.0” encoding=“utf-8”?>
<resources>
<string name=“app_name”>Angry Penguins</string>
<string name=“char_name”>Poppy</string>
<string name=“char_family”>Poppy\’s Family</string>
<string name=“mess”>He says, \“I am mad!\”</string>
<string name=“farewell”>Goodbye for now!</string>
</resources>
Is displayed as:
Is displayed as:
Is displayed as:
Is displayed as:
Is displayed as:
Angry Penguins
Poppy
Poppy’s Family
He says, “I am mad!”
Goodbye for now!
To access a string resource programmatically use the getString() method within your Activity class:
String appTitle = getResources().getString(R.string.app_name);

Colours
You can apply colour resources to screen controls (i.e. buttons, textviews, etc.). Colours are defined by the
<color> tag and identified using the name property. They should be stored in /res/values/colors.xml. The
colors XML file is not created by default. You must add it manually (see Tutorial 1). An example:
<?xml version=“1.0” encoding=“utf-8”?>
<resources>
<color name=“back_color”>#FF00FF</color>
<color name=“title_color”>#800F</color>
<color name=“text_color”>#DD3402</color>
</resources>
Magenta
Blue
Dark Orange
To access a color resource programmatically use the getColor() method within your Activity class:
int colTitle = getResources().getColor(R.color.title_color);

Dimensions
To specify the size of a user interface control such as a Button or TextView, you need to provide different
dimensions. Dimension resources help with setting font size, image size and other physical or pixel-relative
measurements. Dimensions are defined by the <dimen> tag and identified using the name property. They
should be stored in /res/values/dimens.xml. The dimens XML file is not created by default. You must add it
manually (see Tutorial 1). An example:
<?xml version=“1.0” encoding=“utf-8”?>
<resources>
<dimen name=“textSize”>16pt</dimen>
< dimen name=“pic_height”>150px</dimen>
< dimen name=“pic_width”>85px</dimen>
</resources>
All dimension values must end with a unit of measurement:
px – pixels, in – inches, mm – millimeters, pt – points (common font measurement),
dp – density independent pixels (pixels relative to 160 dots per inch)
sp – scale independent pixels (best for scalable font display)
To access a dimension resource programmatically use the getDimension() method within your Activity class:
float photoHeight = getResources().getDimension(R.dimen.pic_height);

Drawables
Drawable resources, such as image files, must be saved under the /res/drawable project directory hierarchy.
Typically apps provide multiple versions of their graphics in order to accommodate different pixel density
screens. By default, an Android project will have: drawable-ldpi (low density), drawable-mdpi (medium density)
and drawable-hdpi (high density). The system will pick the correct version of graphic based on the device
running the app. You must make sure that all versions of a graphic have the SAME name.
You can drag and drop image files into the /res/drawable directory by using the Eclipse Project Explorer.
Filenames must be unique (within the subdirectory), lowercase and contain only letters, numbers and
underscores.
Most common drawables are bitmap-style images. These are often used as app icons or for graphics on a
button. Common formats include: .png – portable network graphics, .jpeg/.jpg – joint photographic experts
group. PNG format is preferred.
Image resources are encapsulated in the class BitmapDrawable. To access a graphic resource file (e.g.
/res/drawable/logo.png) programmatically use the getDrawable() method within your Activity class:
BitmapDrawable logoBitmap = (BitmapDrawable)getResources().getDrawable(R.drawable.logo);
You can also set the drawable for a given control, such as an ImageView, by using the findViewById() method to
retrieve the control and then using the setImageResource to put the graphic in the control.
Suppose there is an ImageView control on a layout that is named imvLogo. In the activity, you can code:
ImageView logoView = (ImageView)findViewById(R.id.imvLogo);
logoView.setImageResource(R.drawable.logo);
Note that there are Drawable subclasses like ShapeDrawable (to define shapes like rectangles and ovals) that
you can use in your app as well.
Working with Layouts
~
Layouts are specially formatted XML files that define the user interface screens for an app. UI layouts are filled with
controls (i.e. CheckBox, Spinner, Button) that interact with the user. Layouts and the controls on them can be
created at runtime using Java (program the Activity class). However, using the XML layout resource files with the
Layout Resource Editor in Eclipse can be easier and better.
Layout resource files are stored in /res/layout. An example:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Droid1MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/greeting"
android:textColor="@color/text_color"
android:textSize="@dimen/textDim" />
</RelativeLayout>
This is a RelativeLayout control
containing a TextView control.

Layout Resource Editor
Eclipse offers a Layout Resource Editor that allows you to drag and drop controls onto your layout, set their
properties and view the results. The xml code above is visually represented as:
Available
controls to
place on the
layout
Outline pane to
add and remove
controls
Properties pane
to set attributes
and
characteristics
of controls
You will probably switch back and forth from this graphical to the xml code. Note that there is a limitation to
this graphical layout mode. If you add a control that is not supported by this tool, you will lose the ability to see
your UI. As well, the editor is not always the most reliable source for interpreting the xml code.
Regardless, you should always test your UI using the AVD emulator.
Learning about Various controls:
http://developer.android.com/guide/topics/ui/index.html
Understanding Layouts:
http://www.learn-android.com/2010/01/05/android-layout-tutorial/

Using Layout Resources Programmatically
Layout controls are derived from the View class. Usually, when programming, you do not need to access an
entire layout, but rather a specific control. For example, you might want to change the text being displayed in a
TextView control.
Any controls that you will be manipulating programmatically should be named a unique identifier. This is done
via the id attribute. For example, you might name a TextView that shows a score: txtScore . To do this:
o Right-click on the TextView control in the Outline Pane. Choose Edit Id... . Type: txtScore
o Or, click on the TextView control on the layout. Type: @id/txtScore in the Id attribute of the Properties
Pane
o Or, type: android:id="@+id/txtScore" within the TextView tag in the xml file
To access a named control in your Activity class for this layout, use the findViewById() method:
TextView userScore = (TextView)findViewById(R.id.txtScore);
Working with Raw Files
~
An app can include raw files as resources. Raw files can include audio files and video files. All raw resource files
should be included in the /res/raw resource directory. All raw file resources must have unique names, excluding the
file suffix (meaning that file1.txt and file1.dat would produce a conflict).
To access a raw file programmatically from within your Activity class, use the openRawResource() method of the
Resource class.
For example, suppose you have a text file: /res/raw/file1.txt . Your code would look like:
InputStream myFile = getResources().openRawResource(R.raw.file1);
For more information on supported media formats, visit:
http://developer.android.com/guide/appendix/media-formats.html
1. Open the My Droid1 Sample in Eclipse.
2. Make the following colors resource modifications:
 Add another new colour to the project in the color.xml file within /res/values. Name it: backgrd_colour
 Choose a hex colour that you like and assign it to this colour
 Now open the main activity and try setting the background of the UI to this new colour
o Try assigning it using the properties window in the Graphical Layout
o Try assigning it within the main xml layout file
 Make sure it works on the emulator
 Practice with colour again by changing the background of the TextView control by going through all the
same steps
3. Make the following drawable resource modification:
 Add another new drawable graphics file (a small PNG or JPG file) which you can drag into one of the
drawable folders; make sure to name appropriately, following convention rules
 Now open the main activity – Graphical Layout view
 Select an ImageView control and place it above the TextView control
o Through the properties, set the ImageView control’s src (source) attribute to the drawable
resource
o Look at the code this generated in the main xml layout file and try to understand it
 Make sure your app works on the emulator and shows the new graphic
4. Play around with the point size of the text in the TextView:
 How small can you make the text so that it is still readable? How large so it still fits?
 What about using px, dp or sp as the unit type. Explore how these measurements work.
 Change the screen density of the emulator through the Settings and see the affect it has on your app.
5. Resave your project.