You are on page 1of 72

Managing Application Resources

Android application composed of :functionality(code or Instruction)


This includes algorithm and behavior of application

Resources
Text String Images Icons Audio files Video files Other data files

What are Resources


You should always externalize resources such as images and strings from your application code, so that you can maintain them independently. It provide alternative resources that support specific device configurations such as different languages or screen sizes, which becomes increasingly important as more Androidpowered devices become available with different configurations.

So, you must organize resources in your project's res/ directory, using various sub-directories that group resources by type and configuration.

Two devices , accessing default resources

Two devices, one of them accessing alternative resources

For example, while your default UI layout is saved in the res/layout/ directory, you might specify a different UI layout to be used when the screen is in landscape orientation, by saving it in the res/layout-land/ directory. Android automatically applies the appropriate resources by matching the device's current configuration to your resource directory names.

Storing Application Resources


Resource files are stored separately from java file. It is stored in XML. We can also store raw data files and graphics as resources.

Resource Directory Hierarchy


Resources organized in /res project directory Sub-directory must be in lowercase. Default Android resource Directories : MyProject/
src/
MyActivity.java

res/
drawable/ icon.png layout/ main.xml info.xml values/ strings.xml // Graphical Resources //User Interface Resources

//Simple data such as Strings, color, array etc

Android Asset packaging Tool


Eclipse, with Android Development tools plug-in, you will find adding resource is very simple. These resources are compiled ,resulting in the generation of R.java file, which enable you to access your resources programmatically. If you use a different development environment then you need to use the appt tool command-line interface to compile your resources and deploy to the phone or emulator .

How resources are resolved


We can organize android project resources based upon : Language and region Screen characteristics (portrait, landscape, small, medium, large) Device modes (dock mode and night mode) Input methods (Touch screen or through keys) Etc.

For any type of resource, you can specify default and multiple alternative resources for your application:
Default resources are those that should be used regardless of the device configuration or when there are no alternative resources that match the current configuration. Alternative resources are those that you've designed for use with a specific configuration. To specify that a group of resources are for a specific configuration, append an appropriate configuration qualifier to the directory name.

Reason for alternative resources : Internationalization and localization (language and region) Application run smoothly on different Device screens and orientation.

Rules to remember when creating alternative resources : If alternative resources does not exist ,the default resource is used. Alternative resources must always be named exactly the same as the default resources.
/res/values/strings.xml /res/values-fr/strings.xml (french) /res/values-zh/strings.xml (Chinese)

Good application design indicaates that alternative resources should always have a default counterpart. Dont go overboard creating alternative resources, they increase size of your application. (use right controls, design your default resources to be flexible and scalable)

Accessing resources Programmatically


/res/values/strings.xml is accessed in code as R.String.strHello String mystring =getResources().getString(R.String.strHello);

Resources classes are present in (android.content.res.Resources)

Resource Types
String Resources: Define strings, string arrays, and plurals (and include string formatting and styling). Saved in res/values/ and accessed from the R.string, R.array, and R.plurals classes.

Style Resources: Define the look and format for UI elements. Saved in res/values/ and accessed from the R.style class.

More Resource Types: Define values such as Booleans, integers, dimensions, colors, and other arrays. Saved in res/values/ but each accessed from unique R sub-classes (such as R.bool, R.integer, R.dimen, etc.).

Animation Resourcess: Define pre-determined animations. Tween animations are saved in res/anim/ and accessed from the R.anim class. Frame animations are saved in res/drawable/ and accessed from the R.drawable class.

Color State List Resourcee: Define a color resources that changes based on the View state. Saved in res/color/ and accessed from the R.color class.

Drawable Resourcess: Define various graphics with bitmaps or XML. Saved in res/drawable/ and accessed from the R.drawable class.

Layout Resourcees: Define the layout for your application UI. Saved in res/layout/ and accessed from the R.layout class.

Menu Resources: Define the contents of your application menus. Saved in res/menu/ and accessed from the R.menu class.

String Resources
A string resource provides text strings for your application There are three types of resources that can provide your application with strings:
String
XML resource that provides a single string.

String Array
XML resource that provides an array of strings.

Quantity Strings (Plurals)


XML resource that carries different strings for different quantities of the same word or phrase.

String A string is a simple resource that is referenced using the value provided in the name attribute file location:
res/values/string.xml

Compiled resource data type:


Resource pointer to a String

resource reference:
In Java: R.string.string_name In XML:@string/string_name

syntax: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="string_name"> text_string</string> </resources> Example <?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">Hello!</string> </resources> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" />

This application code retrieves a string:


String string = getString(R.string.hello);

Formatting Examples String resources value Hello, World users name Displays as Hello, World users name

users name
User\s name

error
users name

\users name\ \user\s name\

users name users name

Bold,Italic and underlined Strings


<b> bold <i> Italic <u> underline

Example: <string name=txt


<b>Bold</b> , <i>Italic</i>, <u>line</u> > </string>

String Resources as Format Strings


Sometimes you may want to create a styled text resource that is also used as a format string.
String.format(String,Object...) method is used for this but it will strip all the style information from the string. This method writes the HTML tags with escaped entities, which are then recovered with fromHtml(String) method. Because the fromHtml(String) method will format all HTML entities, be sure to escape any possible HTML characters in the strings you use with the formatted text, using htmlEncode(String). For instance, if you'll be passing a string argument to String.format() that may contain characters such as "<" or "&", then they must be escaped before formatting, so that when the formatted string is passed through fromHtml(String), the characters come out the way they were originally written

String Resource is <String name=welcome_message> Score: : %1$d of %2$d ! You %3$s . </string>

For including bold or italic, we must put escape sequence as above <string name=welcome_message> Score: %1$d of %2$d ! You&lt; i &gt; %3$s &lt; \i &gt; . </string> You<i> %3$d </i> String res = getResources(). getString(R.string.welcome_messages); String data = TextUtils.htmlEncode(Won);
String resultText = String.format(res, 5,5, data); CharSequence styledText = Html.fromHtml(resultTtext); The resulting Text in styledText will be Score: 5 of 5 ! You<i>Won</i>

String Array
XML file saved at res/values/strings.xml: <?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="planets_array"> <item>Mercury</item> <item>Venus</item> <item>Earth</item> <item>Mars</item> </string-array> </resources> This application code retrieves a string array Resources res = getResources(); String[] planets = res.getStringArray(R.array.planets_array);

Working with Boolean

Working with Boolean


example <?xml version="1.0" encoding="utf-8"?> <resources> <bool name="screen_small">true</bool> <bool name="adjust_view_bounds">true</bool> </resources>

Resources res = getResources(); boolean screenIsSmall = res.getBoolean(R.bool.screen_small);


<ImageView android:layout_height="fill_parent" android:layout_width="fill_parent" android:src="@drawable/logo" android:adjustViewBounds="@bool/adjust_view_bounds" />

Working with Integers


example: XML file saved at res/values/integers.xml:
<?xml version="1.0" encoding="utf-8"?> <resources> <integer name="max_speed">75</integer> <integer name="min_speed">5</integer> </resources> Resources res = getResources(); int maxSpeed = res.getInteger(R.integer.max_speed);

Integer Array

example:

XML file saved at res/values/integers.xml:

<?xml version="1.0" encoding="utf-8"?> <resources> <integer-array name="bits"> <item>4</item> <item>8</item> <item>16</item> <item>32</item> </integer-array> </resources>

Resources res = getResources(); int[] bits = res.getIntArray(R.array.bits);

Working with colors


XML resource that carries a color value (a hexadecimal color). The color is specified with an RGB value and alpha channel. You can use a color resource any place that accepts a hexadecimal color value.

The value always begins with a pound (#) character and then followed by the Alpha-Red-Green-Blue information in one of the following formats:
#RGB (12 bit color) #ARGB (12 bit color with 50% alpha) #RRGGBB (24 bit color ) #AARRGGBB (24 bit color with 50% alpha)

file location:
res/values/colors.xml

resource reference:
In Java: R.color.color_name In XML: @[package:]color/color_name

syntax:
<?xml version="1.0" encoding="utf-8"?> <resources> <color name="color_name" >hex_color</color> </resources>

example: XML file saved at res/values/colors.xml:


<?xml version="1.0" encoding="utf-8"?> <resources> <color name="opaque_red">#f00</color> <color name="translucent_red">#80ff0000</color> </resources>

Resources res = getResources(); int color = res.getColor(R.color.opaque_red); <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textColor="@color/translucent_red" android:text="Hello"/>

Working with Dimensions


A dimension value defined in XML. A dimension is specified with a number followed by a unit of measure. For example: 10px, 2in, 5sp. The following units of measure are supported by Android: dp
Density-independent Pixels based on the physical density of the screen. relative to a 160 dpi (dots per inch) screen, 160dp is always one inch The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion. You should use these units when specifying view dimensions in your layout, so the UI properly scales to render at the same actual size on different screens. (The compiler accepts both "dip" and "dp", though "dp" is more consistent with "sp".)

sp
Scale-independent Pixels this is like the dp unit scaled by the user's font size preference. It is recommend you use this unit when specifying font sizes, so they will be adjusted for both the screen density and the user's preference.

pt
Points 1/72 of an inch based on the physical size of the screen.

mm
Millimeters - based on the physical size of the screen.

px
Pixels corresponds to actual pixels on the screen. This unit of measure is not recommended because the actual representation can vary across devices; each devices may have a different number of pixels per inch and may have more or fewer total pixels available on the screen.

in
Inches based on the physical size of the screen.

Working with simple drawables


paintable drawable resources are defined in XML under the /res/values project directory and compiled into the application package at build time. Paintable drawable resources use the <drawable> tag and represent a name-value pair. <resources> <drawable name=red_rectangle>#F000</drawable> </resources>

you can also create XML files that describe other Drawable subclasses, such as ShapeDrawable. Drawable XML definition files are stored in the /res/drawable directory within your project along with image files.This is not the same as storing <drawable> resources, which are paintable drawables. PaintableDrawable resources are stored in the /res/values directory

<?xml version=1.0 encoding=utf-8?> <shape xmlns:android= http://schemas.android.com/apk/res/android android:shape=oval> <solid android:color=#f00/> </shape>

Working with images


Supported Image Format :Portable Network Graphics (PNG) .png Nine-Patch Stretchable Images.9.png Joint Photographic Experts Group (JPEG) .jpg, .jpeg Graphics Interchange Format (GIF) .gif

These image formats are all well supported by popular graphics editors such as Adobe Photoshop, and Microsoft Paint.The Nine-Patch Stretchable Graphics can be created from PNG files using the draw9patch tool included with the Android SDK under the /tools directory.

Working with Nine-patch Stretchable Graphics


Phone screens come in various dimensions. It can be handy to use stretchable graphics to allow a single graphic that can scale appropriately for different screen sizes and orientations or different lengths of text. This can save you or your designer a lot of time in creating graphics for many different screen sizes Android supports Nine-Patch Stretchable Graphics for this purpose. Nine-Patch graphics are simply PNG graphics that have patches, or areas of the image, defined to scale appropriately, instead of scaling the entire image as one unit. Often the center segment is transparent

For example, if I drop the graphics file flag.png into the /res/drawable directory and add an ImageView control to my main layout
ImageView flagImageView = (ImageView)findViewById(R.id.ImageView01);
flagImageView.setImageResource(R.drawable.flag);

Access the BitmapDrawable object BitmapDrawable bitmapFlag = (BitmapDrawable) getResources().getDrawable(R.drawable.flag); int iBitmapHeightInPixels = bitmapFlag.getIntrinsicHeight(); int iBitmapWidthInPixels = bitmapFlag.getIntrinsicWidth();

Nine-Patch graphics, the call to getDrawable() returns a NinePatchDrawable instead of a BitmapDrawable object.

NinePatchDrawable stretchy = (NinePatchDrawable) getResources().getDrawable(R.drawable.pyramid); int iStretchyHeightInPixels = stretchy.getIntrinsicHeight(); int iStretchyWidthInPixels = stretchy.getIntrinsicWidth();

There is also a special resource type called <selector>, which can be used to define different colors or drawables to be used depending on a controls state. For example, you could define a color state list for a Button control: gray when the button is disabled, green when it is enabled, and yellow when it is being pressed. Similarly, you could provide different drawables based on the state of an ImageButton control.

Working with Animation


An animation resource can define one of two types of animations:
Tween Animation
Creates an animation by performing a series of transformations on a single image. An Animation.

Frame Animation
Creates an animation by showing a sequence of images in order. An AnimationDrawable.

Tween Animation
An animation defined in XML that performs transitions such as rotating, fading, moving, and stretching on a graphic. file location:
res/anim/filename.xml

compiled resource datatype:


Resource pointer to an Animation

resource reference:
In Java: R.anim.filename In XML: @[package:]anim/filename

syntax:
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@[package:]anim/interpolator_resource " android:shareInterpolator=["true" | "false"] > <alpha android:fromAlpha="float" android:toAlpha="float" /> <scale android:fromXScale="float" android:toXScale="float" android:fromYScale="float" android:toYScale="float" android:pivotX="float" android:pivotY="float" />

<translate android:fromXDelta="float" android:toXDelta="float" android:fromYDelta="float" android:toYDelta="float" /> <rotate android:fromDegrees="float" android:toDegrees="float" android:pivotX="float" android:pivotY="float" /> <set> ... </set> </set>

elements: 1) <set>
A container that holds other animation elements (<alpha>,<scale>, <translate>, <rotate>) or other <set> elements. attributes:
android:interpolator
Interpolator resource :- An Interpolator to apply on the animation. An interpolator defines the rate of change of an animation. This allows the basic animation effects (alpha, scale, translate, rotate) to be accelerated, decelerated, repeated, etc. android:shareInterpolator :- Boolean. "true" if you want to share the same interpolator among all child elements.

2) <alpha>
A fade-in or fade-out animation attributes: android:fromAlpha Float. Starting opacity offset, where 0.0 is transparent and 1.0 is opaque. android:toAlpha Float. Ending opacity offset, where 0.0 is transparent and 1.0 is opaque.

3) <scale>
A resizing animation. You can specify the center point of the image from which it grows outward (or inward) by specifying pivotX and pivotY. For example, if these values are 0, 0 (top-left corner), all growth will be down and to the right

attributes:
android:fromXScale
Float. Starting X size offset, where 1.0 is no change.

android:toXScale
Float. Ending X size offset, where 1.0 is no change.

android:fromYScale
Float. Starting Y size offset, where 1.0 is no change.

android:toYScale
Float. Ending Y size offset, where 1.0 is no change.

android:pivotX
Float. The X coordinate to remain fixed when the object is scaled.

android:pivotY
Float. The Y coordinate to remain fixed when the object is scaled.

4) <translate>

A vertical and/or horizontal motion. Supports the following attributes in any of the following three formats. attributes:
android:fromXDelta Float or percentage. Starting X offset. Expressed either: in pixels relative to the normal position , in percentage relative to the element width , or in percentage relative to the parent width . android:toXDelta Float or percentage. Ending X offset. Expressed either: in pixels relative to the normal position , in percentage relative to the element width , or in percentage relative to the parent width . android:fromYDelta Float or percentage. Starting Y offset. Expressed either: in pixels relative to the normal position , in percentage relative to the element height , or in percentage relative to the parent height android:toYDelta Float or percentage. Ending Y offset. Expressed either: in pixels relative to the normal position , in percentage relative to the element height , or in percentage relative to the parent height .

5) <rotate>
A rotation animation. attributes:
android:fromDegrees
Float. Starting angular position, in degrees.

android:toDegrees
Float. Ending angular position, in degrees.

android:pivotX
Float or percentage. The X coordinate of the center of rotation. Expressed either: in pixels relative to the object's left edge (such as "5"), in percentage relative to the object's left edge (such as "5%"), or in percentage relative to the parent container's left edge (such as "5%p").

android:pivotY
Float or percentage. The Y coordinate of the center of rotation. Expressed either: in pixels relative to the object's top edge (such as "5"), in percentage relative to the object's top edge (such as "5%"), or in percentage relative to the parent container's top edge (such as "5%p").

Frame Animation
An animation defined in XML that shows a sequence of images in order (like a film). file location:
res/drawable/filename.xml The filename will be used as the resource ID.

compiled resource datatype:


Resource pointer to an AnimationDrawable.

resource reference:
In Java: R.drawable.filename In XML: @[package:]drawable.filename

syntax:
<?xml version="1.0" encoding="utf-8"?> <animation-list xmlns:android="http://schemas.android.com/apk/res/andr oid" android:oneshot=["true" | "false"] > <item android:drawable="@[package:]drawable/drawable _resource_name" android:duration="integer" /> </animation-list>

elements:
<animation-list>
Required. This must be the root element. Contains one or more <item> elements.attributes: android:oneshot Boolean. "true" if you want to perform the animation once; "false" to loop the animation.

<item> A single frame of animation. Must be a child of a <animation-list> element.attributes: android:drawable


Drawable resource. The drawable to use for this frame. android:duration Integer. The duration to show this frame, in milliseconds.

example:
<?xml version="1.0" encoding="utf-8"?> <animation-list xmlns:android="http://schemas.android.com/apk/res/andr oid" android:oneshot="false"> <item android:drawable="@drawable/rocket_thrust1" android:duration="200" /> <item android:drawable="@drawable/rocket_thrust2" android:duration="200" /> <item android:drawable="@drawable/rocket_thrust3" android:duration="200" /> </animation-list>

This application code will set the animation as the background for a View, then play the animation:ImageView rocketImage = (ImageView) findViewById(R.id.rocket_image); rocketImage.setBackgroundResource(R.drawable.rock et_thrust);
AnimationDrawable rocketAnimation = (AnimationDrawable) rocketImage.getBackground();

rocketAnimation.start();

Working with Menus


A menu resource defines an application menu (Options Menu, Context Menu, or submenu). Menus are an important part of an activity's user interface, which provide users a familiar way to perform actions. There are three types of application menus:
Options Menu
The primary collection of menu items for an activity, which appears when the user touches the MENU button. When your application is running on Android 3.0 or later, you can provide quick access to select menu items by placing them directly in the Action Bar, as "action items."

Context Menu
A floating list of menu items that appears when the user touches and holds a view that's registered to provide a context menu.

Submenu
A floating list of menu items that appears when the user touches a menu item that contains a nested menu.

file location:
res/menu/filename.xml

resource reference:
In Java: R.menu.filename In XML: @[package:]menu.filename

Elements: <menu> :- This must be the root node. Contains <item> and/or <group> elements. <item> :- A menu item. May contain a <menu> element (for a Sub Menu). Must be a child of a < menu> or < group > element.

Attributes of <item> : android:id android:title android:titleCondensed android:icon android:onClick android:alphabeticShortcut android:numericShortcut

To access the menu resource called /res/menu/speed.xml, simply override the method onCreateOptionsMenu() in your application: public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.file, menu); return true; } public boolean onOptionsItemSelected(MenuItem item) {}

public void onCreateContextMenu(android.view.ContextMenu menu, android.view.View v, android.view.ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.file, menu); };

From your application code, you can inflate a menu resource (convert the XML resource into a programmable object) usingMenuInflater.inflate(). For example, the following code inflates the file.xml defined above, during the onCreateOptionsMenu() callback method, to use the menu as the activity's Options Menu: public boolean onContextItemSelected(MenuItem item) {}

<menu xmlns:android =http://schemas.android.com/apk/res/android>


<item
android:id=@+id/start android:title=Start! android:orderInCategory=1>

</item> <item
android:id=@+id/accel android:title=Vroom! Accelerate! android:orderInCategory=3>

</item> <item
android:id=@+id/decel android:title=Decelerate! android:orderInCategory=2>

</item>

</menu>

References to Resources
You can reference resources instead of duplicating them. For example, your application might want to reference a single string resource in multiple string arrays Resources are referenced using the following format:
resource_type/variable_name

<?xml version=1.0 encoding=utf-8?> <resources>


<string-array name=soups> <item>@string/minestrone_soup</item> <item>@string/chowder_soup</item> <item>@string/chicken_soup</item> </string-array>

</resources>

<?xml version=1.0 encoding=utf-8?> <resources>


<string name=app_name>Application Name</string> <string name=chicken_soup >Organic Chicken Noodle</string> <string name=minestrone_soup >Veggie Minestrone</string> <string name=chowder_soup >New England Lobster Chowder</string>

</resources>

You can also use references to make aliases to other resources. For example, you can alias the system resource for the OK string to an application resource name by including the following in your strings.xml resource file:
<?xml version=1.0 encoding=utf-8?> <resources> <string id=app_ok>@android:string/ok</string> </resources>

Working with Layouts


User interface designers can use XML to define Android application screen elements and layout. A layout XML resource is where many different resources come together to form the definition of an Android application screen. Layout resource files are included in the /res/layout/ directory layout file (/res/layout/main.xml) that sets the screens

<?xml version=1.0 encoding=utf-8?> <LinearLayout xmlns:android= http://schemas.android.com/apk/res/android android:orientation=vertical android:layout_width=fill_parent android:layout_height=fill_parent android:background=@color/background_color>
<TextView

android:id=@+id/TextView01 android:layout_width=fill_parent android:layout_height=fill_parent android:text=@string/test_string android:textColor=@color/text_color android:gravity=center android:textSize=@dimen/text_size>


</TextView>

</LinearLayout>

Using Layout Resources Programmatically :XmlResourceParser myMainXml = getResources().getLayout(R.layout.main);

Working with Xml


XML files are store in the /res/xml directory, and they are compiled into the application package at build time. Example my_pets.xml
<?xml version=1.0 encoding=utf-8?> <pets>
<pet name=Bit type=Bunny /> <pet name=Nibble type=Bunny /> <pet name=Stack type=Bunny /> <pet name=Queue type=Bunny /> <pet name=Heap type=Bunny /> <pet name=Null type=Bunny /> <pet name=Nigiri type=Fish /> <pet name=Sashimi II type=Fish /> <pet name=Kiwi type=Lovebird />

</pets>

you can access this XML file as a resource programmatically in the following manner:
XmlResourceParser myPets = getResources().getXml(R.xml.my_pets);

one way to extract the information from xml


int eventType = -1; while (eventType != XmlResourceParser.END_DOCUMENT) {
if(eventType == XmlResourceParser.START_DOCUMENT) {
Log.d(DEBUG_TAG, Document Start);

} else if(eventType == XmlResourceParser.START_TAG) {


String strName = myPets.getName();

if(strName.equals(pet)) { Log.d(DEBUG_TAG, Found a PET); Log.d(DEBUG_TAG,Name: +myPets.getAttributeValue(null, name)); Log.d(DEBUG_TAG, Species: +myPets.getAttributeValue(null, type)); //attributeSet }

} eventType = myPets.next();
} Log.d(DEBUG_TAG, Document End);

Working with Raw files


raw files are such as audio files, video files, and other file formats not supported by the Android Resource packaging tool aapt. All raw resource files are included in the /res/raw directory and are added to your package without further processing. The resource filename must be unique to the directory and should be descriptive because the filename (without the extension) becomes the name by which the resource is accessed. Heres one way to open a file called the_help.txt:
InputStream iFile = getResources() . openRawResource(R.raw.the_help);

You might also like