Professional Documents
Culture Documents
Resources
Text String Images Icons Audio files Video files Other data files
So, you must organize resources in your project's res/ directory, using various sub-directories that group resources by type and configuration.
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.
res/
drawable/ icon.png layout/ main.xml info.xml values/ strings.xml // Graphical Resources //User Interface Resources
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)
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.
String A string is a simple resource that is referenced using the value provided in the name attribute file location:
res/values/string.xml
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" />
Formatting Examples String resources value Hello, World users name Displays as Hello, World users name
users name
User\s name
error
users name
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< i > %3$s < \i > . </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);
Integer Array
example:
<?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>
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>
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"/>
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.
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>
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.
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.
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
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.
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.
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();
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.
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) {}
</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
</resources>
</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>
<?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
</LinearLayout>
</pets>
you can access this XML file as a resource programmatically in the following manner:
XmlResourceParser myPets = getResources().getXml(R.xml.my_pets);
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);