This page describes all the different types of resources that you can externalize from your code and package with your application. They fall into the following groups:
For more details on how to use resources in your application, please see the Resources and i18n documentation.
All simple resource values can be expressed as a string, using various formats to unambiguously indicate the type of resource being created. For this reason, these values can be defined both as standard resources (under res/values), as well as direct values supplied for mappings in styles and themes, and attributes in XML files such as layouts.
A color value specifies an RGB value with an alpha channel, which can be used in various places such as specifying a solid color for a Drawable or the color to use for text. A color value always begins with a '#' character and then is followed by the alpha-red-green-blue information in one of the following formats:
If you want to retrieve the color represented by a resource ID, you can call the Resources.getColor() method.
Source file format: XML file requiring a
<?xml version="1.0" encoding="utf-8"?>
declaration, and
a root <resources>
element containing one or more
<color>
tags.
Resource source file location: res/values/colors.xml (file name is arbitrary)
Compiled resource datatype: Resource pointer to a Java int.
Resource reference name:
R.color.some_name
@[package:]color/some_name
(where some_name is the name of a specific color)
Syntax
<color name=color_name>#color_value</color>
Example XML Declaration
The following code declares two colors, the first fully opaque, and the second translucent.
<resources> <color name="opaque_red">#f00</color> <color name="translucent_red">#80ff0000</color> </resources>
Example Code Use
Example Java code
// Retrieve a color value. int color = getResources.getColor(R.color.opaque_red);
Example XML code
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textAlign="center" android:textColor="@color/translucent_red" android:text="Some Text"/>
Strings, with optional simple formatting, can be
stored and retrieved as resources. You can add formatting to your string by
using three standard HTML tags: <b>, <i>, and <u>. To
guarantee getting an unstyled string only (the raw text) call the
toString()
method of the retrieved CharSequence object.
Methods that accept string resources should be able to process these styling
tags.
If you want to retrieve the String represented by a resource ID, you can call the Context.getString() method.
Note: If you use an apostrophe or a quote in your string, you must either escape it or enclose the whole string in the other kind of enclosing quotes:
<string name="good_example">"This'll work"</string> <string name="good_example_2">This\'ll also work</string> <string name="bad_example">This won't work!</string> <string name="bad_example_2">XML encodings won't work either!</string>
Source file format: XML file requiring a <?xml version="1.0" encoding="utf-8"?>
declaration, and a root <resources>
element containing one or more <string>
tags.
Resource source file location: res/values/strings.xml (file name is arbitrary)
Compiled resource datatype: Resource pointer to a Java CharSequence.
Resource reference name:
R.string.some_name
@[package:]string/some_name
(where some_name is the name of a specific string)
Syntax
<string name=string_name>string_value</string>
Example XML Declaration
The following declares two strings: the first — simple text with no formatting (resulting in a CharSequence that is simply a String object) — the second includes formatting information in the string (resulting in a CharSequence that is a complex data structure). If you are using the custom editor for string files in Eclipse, the HTML formatting tags will automatically be escaped and you will need to use Context.getString() and fromHtml(String) to retreive the resource and then convert it to formatted text.
<resources> <string name="simple_welcome_message">Welcome!</string> <string name="styled_welcome_message">We are <b><i>so</i></b> glad to see you.</string> </resources>
Example Code Use
Example Java code
// Assign a styled string resource to a TextView // on the current screen. CharSequence str = getString(R.string.styled_welcome_message); TextView tv = (TextView)findViewByID(R.id.text); tv.setText(str);
Example XML code
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textAlign="center" android:text="@string/simple_welcome_message"/>
Sometimes you may want to create a styled text resource that is also used as a format string. This cannot be done directly because there is no way of passing the styled text as the format string argument of String.format() without stripping out the style information. The workaround is to store the style tags as escaped HTML tags, and then convert the escaped HTML string into a styled text after formatting has taken place.
To use styled text as a format string, do the following.
<resources> <string name="search_results_resultsTextFormat">%1$d results for <b>&quot;%2$s&quot;</b></string> </resources>
In this example the format string has two arguments: %1$d
is a decimal number, %2$s
is a string.
String escapedTitle = TextUtil.htmlEncode(title);
String resultsTextFormat = getContext().getResources().getString(R.string.search_results_resultsTextFormat); String resultsText = String.format(resultsTextFormat, count, escapedTitle); CharSequence styledResults = Html.fromHtml(resultsText);
You can create common dimensions to use for various screen elements by defining dimension values in XML. A dimension resource is a number followed by a unit of measurement. For example: 10px, 2in, 5sp. Here are the units of measurement supported by Android:
Dimension values are not normally used as raw resources, but rather as attribute values in XML files. You can, however, create plain resources containing this data type.
Source file format: XML file requiring a <?xml
version="1.0" encoding="utf-8"?>
declaration, and a root
<resources>
element containing one or more
<dimen>
tags.
Resource source file location: res/values/dimens.xml (File name is arbitrary; standard practice is to put all dimensions in one file devoted to dimensions.)
Compiled resource datatype: Resource pointer to a dimension.
Resource reference name:
R.dimen.some_name
@[package:]dimen/some_name
(where some_name is the name of a specific <dimen>
element)
Syntax
<dimen name=dimen_name>dimen_value</dimen>
Example XML Declaration
The following code declares several dimension values.
<resources> <dimen name="one_pixel">1px</dimen> <dimen name="double_density">2dp</dimen> <dimen name="sixteen_sp">16sp</dimen> </resources>
Example Code Use
Example Java code:
float dimen = Resources.getDimen(R.dimen.one_pixel);
Example XML code:
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="@dimen/sixteen_sp"/>
A Drawable is a type of resource that you retrieve with Resources.getDrawable() and use to draw to the screen. There are a number of drawable resources that can be created.
Android supports bitmap resource files in a few different formats: png (preferred), jpg (acceptable), gif (discouraged). The bitmap file itself is compiled and referenced by the file name without the extension (so res/drawable/my_picture.png would be referenced as R.drawable.my_picture).
Source file formats: png (preferred), jpg (acceptable), gif (discouraged). One resource per file.
Resource file location: res/drawable/some_file.png or some_file.jpg or some_file.gif.
Compiled resource datatype: Resource pointer to a BitmapDrawable.
Resource reference name:
R.drawable.some_file
@[package:]drawable/some_file
Example Code Use
The following Java snippet demonstrates loading an ImageView object with a single bitmap from a list of bitmap resources. ImageView is a basic display rectangle for graphics (animations or still images).
// Load an array with BitmapDrawable resources. private Integer[] mThumbIds = { R.drawable.sample_thumb_0, R.drawable.sample_thumb_1, R.drawable.sample_thumb_2, R.drawable.sample_thumb_3, R.drawable.sample_thumb_4 }; // Load and return a view with an image. public View getView(int position, ViewGroup parent) { ImageView i = new ImageView(mContext); i.setImageResource(mThumbIds[position]); i.setAdjustViewBounds(true); i.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); i.setBackground(android.R.drawable.picture_frame); return i; }
This XML example demonstrates loading a bitmap file (chat_icon.png) in an ImageView.
<ImageView id="@+id/icon" android:layout_width="wrap_content" android:layout_height="wrap_content" android:tint="#FF000000" android:src="@drawable/chat_icon"/>
You can create a PaintDrawable object that is a rectangle of color, with optionally rounded corners. This element can be defined in any of the files inside res/values/.
Source file format: XML file requiring a <?xml
version="1.0" encoding="utf-8"?>
declaration, and a root
<resources>
element containing one or more
<drawable>
tags.
Resource source file location: res/values/colors.xml (File name is arbitrary; standard practice is to put the PaintDrawable items in the file along with the numeric color values.)
Compiled resource datatype: Resource pointer to a PaintDrawable.
Resource reference name:
R.drawable.some_name
@[package:]drawable/some_name
(where some_name is the name of a specific resource)
Syntax
<drawable name=color_name>color_value</drawable>
Example XML Declaration
The following code declares several color drawables.
<resources> <drawable name="solid_red">#f00</drawable> <drawable name="solid_blue">#0000ff</drawable> <drawable name="solid_green">#f0f0</drawable> </resources>
Example Code Use
Example Java code
// Assign a PaintDrawable as the background to // a TextView on the current screen. Drawable redDrawable = Resources.getDrawable(R.drawable.solid_red); TextView tv = (TextView)findViewByID(R.id.text); tv.setBackground(redDrawable);
Example XML code
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textAlign="center" android:background="@drawable/solid_red"/>
Android supports a stretchable bitmap image, called a NinePatch graphic. This is a PNG image in which you define stretchable sections that Android will resize to fit the object at display time to accommodate variable sized sections, such as text strings. You typically assign this resource to the View's background. An example use of a stretchable image is the button backgrounds that Android uses; buttons must stretch to accommodate strings of various lengths.
A NinePatch drawing is a standard PNG image that includes a 1 pixel wide border. This border is used to define the stretchable and static areas of the screen. You indicate a stretchable section by drawing one or more 1 pixel wide black lines in the left or top part of this border. You can have as many stretchable sections as you want. The relative size of the stretchable sections stays the same, so the largest sections always remain the largest.
You can also define an optional drawable section of the image (effectively, the padding lines) by drawing a line on the right and bottom lines. If you do not draw these lines, the first top and left lines will be used.
If a View object sets this graphic as a background and then specifies the View object's text, it will stretch itself so that all the text fits inside the area designated by the right and bottom lines (if included). If the padding lines are not included, Android uses the left and top lines to define the writeable area.
The Draw 9-patch tool offers an extremely handy way to create your NinePatch images, using a WYSIWYG graphics editor.
Here is a sample NinePatch file used to define a button.
This ninepatch uses one single stretchable area, and it also defines a drawable area.
Source file format: PNG — one resource per file
Resource source file location: res/drawable/some_name.9.png (must end in .9.png)
Compiled resource datatype: Resource pointer to a NinePatchDrawable.
Resource reference name:
R.drawable.some_file
@[package:]drawable.some_file
Example XML Code
Note that the width and height are set to "wrap_content" to make the button fit neatly around the text.
<Button id="@+id/tiny" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerInParent="true" android:text="Tiny" android:textSize="8sp" android:background="@drawable/my_button_background"/> <Button id="@+id/big" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerInParent="true" android:text="Biiiiiiig text!" android:textSize="30sp" android:background="@drawable/my_button_background"/>
Here are the two buttons based on this XML and the NinePatch graphic shown above. Notice how the width and height of the button varies with the text, and the background image stretches to accommodate it.
Android can perform simple animation on a graphic, or a series of graphics. These include rotations, fading, moving, and stretching.
Source file format: XML file, one resource per file, one root tag with no <?xml>
declaration
Resource file location: res/anim/some_file.xml
Compiled resource datatype: Resource pointer to an Animation.
Resource reference name:
R.anim.some_file
@[package:]anim/some_file
Syntax
The file must have a single root element: this will be either a single <alpha>
, <scale>
, <translate>
, <rotate>
, interpolator element, or <set>
element that holds groups of these elements (which may include another <set>
). By default, all elements are applied simultaneously. To have them occur sequentially, you must specify the startOffset
attribute, as shown in the example code.
<set android:shareInterpolator=boolean> // Only required if multiple tags are used. <alpha android:fromAlpha=float android:toAlpha=float > | <scale android:fromXScale=float android:toXScale=float android:fromYScale=float android:toYScale=float android:pivotX=string android:pivotY=string> | <translate android:fromX=string android:toX=string android:fromY=string android:toY=string> | <rotate android:fromDegrees=float android:toDegrees=float android:pivotX=string android:pivotY=string /> | <interpolator tag> <set> </set>
Elements and Attributes
scale
supports the following attributes:
Note that alpha, scale, rotate, translate all support the following attributes from the base animation class, BaseAnimation:
Example XML Declaration
The following XML from the ApiDemos application is used to stretch, then simultaneously spin and rotate a block of text.
<set android:shareInterpolator="false"> <scale android:interpolator="@android:anim/ease_in_out_interpolator" android:fromXScale="1.0" android:toXScale="1.4" android:fromYScale="1.0" android:toYScale="0.6" android:pivotX="50%" android:pivotY="50%" android:fillAfter="false" android:duration="700" /> <set android:interpolator="@android:anim/ease_in_interpolator"> <scale android:fromXScale="1.4" android:toXScale="0.0" android:fromYScale="0.6" android:toYScale="0.0" android:pivotX="50%" android:pivotY="50%" android:startOffset="700" android:duration="400" android:fillBefore="false" /> <rotate android:fromDegrees="0" android:toDegrees="-45" android:toYScale="0.0" android:pivotX="50%" android:pivotY="50%" android:startOffset="700" android:duration="400" /> </set> </set>
The following Java code loads animations called res/anim/hyperspace_in.xml and res/anim/hyperspace_out.xml into a ViewFlipper.
mFlipper.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.hyperspace_in)); mFlipper.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.hyperspace_out));
Android lets you specify screen layouts using XML elements inside an XML file, similar to designing screen layout for a webpage in an HTML file. Each file contains a whole screen or a part of a screen, and is compiled into a View resource that can be passed in to Activity.setContentView or used as a reference by other layout resource elements. Files are saved in the res/layout/ folder of your project, and compiled by the Android resource compiler aapt.
Every layout XML file must evaluate to a single root element. First we'll describe how to use the standard XML tags understood by Android as it is shipped, and then we'll give a little information on how you can define your own custom XML elements for custom View objects. See Implementing a User Interface for details about the visual elements that make up a screen.
The root element must have the Android namespace "http://schemas.android.com/apk/res/android" defined in the root element
Source file format: XML file requiring a <?xml version="1.0" encoding="utf-8"?>
declaration, and a root element of one of the supported XML layout elements.
Resource file location: res/layout/some_file.xml.
Compiled resource datatype: Resource pointer to a View (or subclass) resource.
Resource reference name:
R.drawable.some_file
@[package:]layout/some_file
Syntax
<ViewGroupClass xmlns:android="http://schemas.android.com/apk/res/android" id="@+id/string_name" (attributes)> <widget or other nested ViewGroupClass>+ <requestFocus/>(0 or 1 per layout file, assigned to any element) </ViewGroupClass>
The file must have a single root element. This can be a ViewGroup class that contains other elements, or a widget (or custom item) if it's only one object. By default, you can use any (case-sensitive) Android widget or ViewGroup class name as an element. These elements support attributes that apply to the underlying class, but the naming is not as clear. How to discover what attributes are supported for what tags is discussed below. You should not assume that any nesting is valid (for example you cannot enclose <TextView>
elements inside a <ListLayout>
).
If a class derives from another class, the XML element inherits all the attributes from the element that it "derives" from. So, for example, <EditText>
is the corresponding XML element for the EditText class. It exposes its own unique attributes (EditText_numeric
), as well as all attributes supported by <TextView>
and <View>
. For the id attribute of a tag in XML, you should use a special syntax: "@+id/somestringvalue". The "@+" syntax creates a resource number in the R.id class, if one doesn't exist, or uses it, if it does exist. When declaring an ID value for an XML tag, use this syntax. Example: <TextView id="@+id/nameTextbox"/>
, and refer to it this way in Java: findViewById(R.id.nameTextbox)
. All elements support the following values:
xmlns:android="http://schemas.android.com/apk/res/android"
- Required for the root element only.
What Attributes Are Supported for What Elements?
Android uses the LayoutInflater class at run time to load an XML layout resource and translate it into visual elements. By default, all widget class names are supported directly as tags, but a full list of supported tags and attributes is listed in the R.styleable reference page. However, the attribute names are somewhat obscure. If an underscore appears in the name, this indicates that it is an attribute — typically of the element before the underscore. So, for example, EditText_autoText
means that the <EditText>
tag supports an attribute autoText. When you actually use the attribute in that element, use only the portion after the last underscore, and prefix the attribute with the prefix "android:
". So, for example, if R.styleable lists the following values:
TextView
TextView_lines
TextView_maxlines
You could create an element like this:
<TextView android:lines="10" android:maxlines="20"/>
This would create a TextView object and set its lines and maxlines properties.
Attributes come from three sources:
TextView
supports TextView_text
, as discussed above.
<TextView>
element supports all the attributes that the <View>
element exposes — a long list, including View_paddingBottom
and View_scrollbars
. These too are used without the class name: <TextView android:paddingBottom="20" android:scrollbars="horizontal" />
.
android:layout_gravity
for an object wrapped by a <LinearLayout>
element. Remember that each LayoutParams subclass also supports inherited attributes. Attributes exposed by each subclass are given in the format someLayoutParamsSubclass_Layout_layout_someproperty. This defines an attribute "android:layout_someproperty". Here is an example of how Android documentation lists the properties of the LinearLayout.LayoutParams class:
gravity
attribute
height
attribute
weight
attribute
width
attribute
Here is an example that sets some of these values on a few objects, including direct attributes, inherited attributes, and LayoutParams attributes:
<?xml version="1.0" encoding="utf-8"?> <!-- res/main_screen.xml --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" // The object's own orientation property android:padding="4" // Inherited View property android:gravity="center" // The object's own property android:layout_width="fill_parent" // Parent object's LinearLayout.LayoutParams.width android:layout_height="fill_parent"> // Parent object's LinearLayout.LayoutParams.height <TextView android:layout_width="fill_parent" // TextView.LayoutParams.width android:layout_height="wrap_content" // TextView.LayoutParams.height android:layout_weight="0" // TextView.LayoutParams.weight android:paddingBottom="4" // TextView.paddingBottom android:text="@string/redirect_getter"/> // TextView.text <EditText id="@+id/text" android:layout_width="fill_parent" // EditText.LayoutParams.width android:layout_height="wrap_content" // EditText.LayoutParams.height android:layout_weight="0" // EditText.LinearLayoutParams.weight android:paddingBottom="4"> // EditText.paddingBottom <requestFocus /> </EditText> <Button id="@+id/apply" android:layout_width="wrap_content" // Button.LayoutParams.width android:layout_height="wrap_content" // Button.LayoutParams.height android:text="@string/apply" /> // TextView.text </LinearLayout>
Example Code Use
The most common use is to load the XML file (located at res/main_screen.xml) and use it as the current screen, as shown here with the preceding file:
setContentView(R.layout.main_screen);
However, layout elements can also represent repeating elements used as templates.
You can define custom elements to use in layout resources. These custom elements can then be used the same as any Android layout elements: that is, you can use them and specify their attributes in other resources. The ApiDemos sample application has an example of creating a custom layout XML tag, LabelView. To create a custom element, you will need the following files:
<declare-styleable id=your_java_class_name>
. See res/layout/attrs.xml in ApiDemos.
Source file format: XML file without an <?xml>
declaration, and a <resources>
root element containing one or more custom element tags.
Resource file location: res/values/attrs.xml (file name is arbitrary).
Compiled resource datatype: Resource pointer to a View (or subclass) resource.
Resource reference name: R.styleable.some_file (Java).
A style is one or more attributes applied to a single element (for example, 10 point red Arial font, applied to a TextView). A style is applied as an attribute to an element in a layout XML file.
A theme is one or more attributes applied to a whole screen — for example, you might apply the stock Android Theme.dialog theme to an activity designed to be a floating dialog box. A theme is assigned as an attribute to an Activity in the manifest file.
Both styles and themes are defined in a <style> block containing one or more string or numerical values (typically color values), or references to other resources (drawables and so on). These elements support inheritance, so you could have MyBaseTheme, MyBaseTheme.Fancy, MyBaseTheme.Small, and so on.
Source file format: XML file requiring a <?xml version="1.0" encoding="utf-8"?>
declaration, and a root <resources>
element containing one or more <style>
tags.
Resource source file location: res/values/styles.xml (file name is arbitrary). The file name is arbitrary, but standard practice is to put all styles into a file named styles.xml.
Compiled resource datatype: Resource pointer to a Java CharSequence.
Resource reference name:
R.style.styleID
for the whole style, R.style.styleID.itemID
for an individual setting
@[package:]style/styleID
for a whole style, @[package:]style/styleID/itemID
for an individual item. Note: to refer to a value in the currently applied theme, use "?" instead of "@" as described below (XML).
Syntax
<style name=string [parent=string] > <item name=string>Hex value | string value | reference</item>+ </style>
android:Theme
for the base Android theme, or MyTheme
for a theme defined in your package).
Example XML Declaration of a Style
<?xml version="1.0" encoding="utf-8"?> <resources> <style name="SpecialText"> <item name="android:textSize">18sp</item> <item name="android:textColor">#008</item> </style> </resources>
Example Code Use of a Style
The following layout XML file applies the previously defined style to a single text box.
<!-- MainPageLayout.xml --> <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="fill_parent" android:layout_width="fill_parent" android:orientation="vertical" android:scrollbars="vertical" id="main_frame"> <EditText id="@+id/text1" style="@style/SpecialText" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Hello, World!" /> </LinearLayout>
Example XML Declaration of a Theme
The following example defines a theme, "ThemeNew," which creates new theme items, refers to some previously defined theme items (those in bold), and and refers to package resources (those in italics).
<style name="ThemeNew"> <item name="windowFrame">@drawable/screen_frame</item> <item name="windowBackground">@drawable/screen_background_white</item> <item name="panelForegroundColor">#FF000000</item> <item name="panelBackgroundColor">#FFFFFFFF</item> <item name="panelTextColor">?panelForegroundColor</item> <item name="panelTextSize">14</item> <item name="menuItemTextColor">?panelTextColor</item> <item name="menuItemTextSize">?panelTextSize</item> </style>
Notice that, to reference a value from the currently loaded theme, we use
a question-mark (?) instead of the at-symbol (@), in the reference string.
You must refer to such a specific <item>
by its name in
the currently loaded theme. This can be used in XML resources only.
Example Code Use of a Theme
The following Java snippet demonstrates loading a style set (i.e., a theme).
setTheme(R.style.ThemeNew);
The following XML applies an Android theme to a whole file (in this case, the Android dialog theme, to make the screen a floating dialog screen).
<!-- AndroidManifest.xml --> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.codelab.rssexample"> <activity class="AddRssItem" android:label="@string/add_item_label" android:theme="@android:style/Theme.Dialog"/> </manifest>