Available Resource Types | Android Developers
来源:百度文库 编辑:神马文学网 时间:2024/04/29 10:56:49
Available Resource Types
Key classes
Resources
AssetManager
In this document
Simple ValuesColor Values
Strings and Styled Text
Dimension Values
DrawablesBitmap Files
Color Drawables
Nine-Patch (Stretchable) Images
Animation
Menus
LayoutCustom Layout Resources
Styles and Themes
Searchable
This page describes the different types of resources that you can externalize from your code and package with your application.
For more details on how to use resources in your application, please see theResources and Internationalization documentation.
Simple Values
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 instyles and themes, and attributes in XML files such aslayouts.
Color Values
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 aDrawable or the color to use for text. A color value always begins with a pound (#) character and then followed by the Alpha-Red-Green-Blue information in one of the following formats:
#RGB #ARGB #RRGGBB #AARRGGBB
If you want to retrieve the color represented by a resource ID, you can call theResources.getColor() method.
Source file format: XML file requiring a declaration, and a root element containing one or more 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:
Java: R.color.some_name
XML: @[package:]color/some_name (where some_name is the name of a specific color)
Syntax
#color_value
Value is a color, using web-style syntax, as describe above. Has only one attribute: name - The name used in referring to this color.
Example XML Declaration
The following code declares two colors, the first fully opaque, and the second translucent.
#f00 #80ff0000
Example Code Use
Example Java code
// Retrieve a color value.int color = getResources.getColor(R.color.opaque_red);
Example XML code
Strings and Styled Text
Strings, with optionalsimple formatting, can be stored and retrieved as resources. You can add formatting to your string by using three standard HTML tags: , , and . 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 theContext.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:
"This'll work" This\'ll also work This won't work! XML encodings won't work either!
Source file format: XML file requiring a declaration, and a root element containing one or more 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:
Java: R.string.some_name
XML: @[package:]string/some_name (where some_name is the name of a specific string)
Syntax
string_value
Value is a string, with optional styling tags. Has only one attribute: name - The name used in referring to this 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 useContext.getString() andfromHtml(String) to retreive the resource and then convert it to formatted text.
Welcome! We are so glad to see you.
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
Using Styled Text as a Format String
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.
Store your styled text resource as an escaped string, so that the HTML tags in your text resource are not interpreted as if they were XML tags: %1$d results for <b>"%2$s"</b>
In this example the format string has two arguments: %1$d is a decimal number, %2$s is a string.
Make sure any String arguments are properly escaped if they might contain '<' or '&' characters. ThehtmlEncode(String) method will do this: String escapedTitle = TextUtil.htmlEncode(title);
Use String.format() to format the HTML text, then usefromHtml(String) to convert the HTML text into styled text: 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:
px
Pixels - corresponds to actual pixels on the screen.
in
Inches - based on the physical size of the screen.
mm
Millimeters - based on the physical size of the screen.
pt
Points - 1/72 of an inch based on the physical size of the screen.
dp
Density-independent Pixels - an abstract unit that is based on the physical density of the screen. These units are relative to a 160 dpi screen, so one dp is one pixel on a 160 dpi screen. The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion. Note: The compiler accepts both "dip" and "dp", though "dp" is more consistent with "sp".
sp
Scale-independent Pixels - this is like the dp unit, but it is also 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 user's preference.
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 declaration, and a root element containing one or more tags.
Resource source file location: res/values/dimens.xml (File name is arbitrary, but standard practice is to put all dimensions in one file devoted to dimensions.)
Compiled resource datatype: Resource pointer to a dimension.
Resource reference name:
Java: R.dimen.some_name
XML: @[package:]dimen/some_name (where some_name is the name of a specific element)
Syntax
dimen_value
A valid dimension value. name - The name used in referring to this dimension.
Example XML Declaration
The following code declares several dimension values.
1px 2dp 16sp
Example Code Use
Example Java code:
float dimen = Resources.getDimen(R.dimen.one_pixel);
Example XML code:
Drawables
ADrawable is a type of resource that you retrieve withResources.getDrawable() and use to draw to the screen. There are a number of drawable resources that can be created.
Bitmap Files
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
Compiled resource datatype: Resource pointer to aBitmapDrawable.
Resource reference name:
Java: R.drawable.some_file
XML: @[package:]drawable/some_file
For more discussion and examples using drawable resources, see the discussion in2D Graphics.
Color Drawables
You can create aPaintDrawable 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 declaration, and a root element containing one or more tags.
Resource source file location: res/values/colors.xml (File name is arbitrary, but standard practice is to put the PaintDrawable items in the file along with thenumeric color values.)
Compiled resource datatype: Resource pointer to aPaintDrawable.
Resource reference name:
Java: R.drawable.some_name
XML: @[package:]drawable/some_name (where some_name is the name of a specific resource)
Syntax
color_value
A validcolor value. name - The name used in referring to this drawable.
Example XML Declaration
The following code declares several color drawables.
#f00 #0000ff #f0f0
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
Nine-Patch (stretchable) Images
Android supports a stretchable bitmap image, called aNinePatch 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.
Source file format: PNG — one resource per file
Resource source file location: res/drawable/some_name.9.png (Filename must end in .9.png)
Compiled resource datatype: Resource pointer to aNinePatchDrawable.
Resource reference name:
Java: R.drawable.some_file
XML: @[package:]drawable.some_file
For more information and examples using NinePatch drawables, see the discussion in2D Graphics.
Animation
Tweened Animation
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 declaration
Resource file location: res/anim/some_file.xml
Compiled resource datatype: Resource pointer to anAnimation.
Resource reference name:
Java: R.anim.some_file
XML: @[package:]anim/some_file
Syntax
The file must have a single root element: this will be either a single, , , , interpolator element, or element that holds groups of these elements (which may include another ). By default, all elements are applied simultaneously. To have them occur sequentially, you must specify the startOffset attribute.
// Only required if multiple tags are used. | | | |
Elements and Attributes
A container that can recursively hold itself or other animations. Represents anAnimationSet. You can include as many child elements of the same or different types as you like. Supports the following attribute: shareInterpolator - Whether to share the same Interpolator among all immediate child elements.
A fading animation. Represents anAlphaAnimation. Supports the following attributes: fromAlpha - 0.0 to 1.0, where 0.0 is transparent.
toAlpha - 0.0 to 1.0, where 0.0 is transparent.
A resizing animation. Represents aScaleAnimation. You can specify what is the center point of the image (the pinned center), from which it grows outward (or inward), by specifying pivotX and pivotY. So, for example, if these were 0, 0 (top left corner), all growth would be down and to the right. scale supports the following attributes: fromXScale - Starting X size, where 1.0 is no change.
toXScale - Ending X size, where 1.0 is no change.
fromYScale - Starting Y size, where 1.0 is no change.
toYScale - Ending Y size, where 1.0 is no change.
pivotX - The X coordinate of the pinned center.
pivotY - The Y coordinate of the pinned center.
A vertical/horizontal motion animation. Represents aTranslateAnimation. Supports the following attributes in any of the following three formats: values from -100 to 100, ending with "%", indicating a percentage relative to itself; values from -100 to 100, ending in "%p", indicating a percentage relative to its parent; a float with no suffix, indicating an absolute value. fromXDelta - Starting X location.
toXDelta - Ending X location.
fromYDelta - Starting Y location.
toYDelta - Ending Y location.
A rotation animation. Represents aRotateAnimation. Supports the following attributes: fromDegrees - Starting rotation, in degrees.
toDegrees - Ending rotation, in degrees.
pivotX - The X coordinate of the center of rotation, in pixels, where (0,0) is the top left corner.
pivotY - The Y coordinate of the center of rotation, in pixels, where (0,0) is the top left corner.
You can also use any of the interpolator subclass elements defined inR.styleable. Examples include, , and . These objects define a velocity curve that describes how quickly a visual action takes place on a timeline (fast at first and slow later, slow at first and gradually faster, and so on).
In addition to the attributes defined for each element above, the elements, , , , and all support the following attributes (inherited from theAnimation class):
duration
Duration, in milliseconds, for this effect.
startOffset
Offset start time for this effect, in milliseconds.
fillBefore
When set true, the animation transformation is applied before the animation begins.
fillAfter
When set true, the animation transformation is applied after the animation ends.
repeatCount
Defines the number of times the animation should repeat.
repeatMode
Defines the animation behavior when it reaches the end and the repeat count is greater than 0. Options are to either restart or reverse the animation.
zAdjustment
Defines the z-axis ordering mode to use when running the animation (normal, top, or bottom).
interpolator
You can optionally set an interpolator for each element to determine how quickly or slowly it performs its effect over time. For example, slow at the beginning and faster at the end for EaseInInterpolator, and the reverse for EaseOutInterpolator. A list of interpolators is given inR.anim. To specify these, use the syntax @android:anim/interpolatorName.
For more discussion and animation code samples, see the discussion in the2D Graphics document.
Menus
Application menus (Options Menu, Context Menu, or Sub Menu) can be defined as XML resources and inflated by your application usingMenuInflater.
Source file format: XML file, one resource per file, one root tag, declaration not required.
Resource file location: res/menu/some_file.xml
Compiled resource datatype: Resource pointer to aMenu (or subclass) resource.
Resource reference name:
Java: R.menu.some_file
Syntax
The file must have a single root element: a
Key classes
Resources
AssetManager
In this document
Simple ValuesColor Values
Strings and Styled Text
Dimension Values
DrawablesBitmap Files
Color Drawables
Nine-Patch (Stretchable) Images
Animation
Menus
LayoutCustom Layout Resources
Styles and Themes
Searchable
This page describes the different types of resources that you can externalize from your code and package with your application.
For more details on how to use resources in your application, please see theResources and Internationalization documentation.
Simple Values
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 instyles and themes, and attributes in XML files such aslayouts.
Color Values
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 aDrawable or the color to use for text. A color value always begins with a pound (#) character and then followed by the Alpha-Red-Green-Blue information in one of the following formats:
#RGB #ARGB #RRGGBB #AARRGGBB
If you want to retrieve the color represented by a resource ID, you can call theResources.getColor() method.
Source file format: XML file requiring a declaration, and a root
Resource source file location: res/values/colors.xml (File name is arbitrary.)
Compiled resource datatype: Resource pointer to a Java int.
Resource reference name:
Java: R.color.some_name
XML: @[package:]color/some_name (where some_name is the name of a specific color)
Syntax
Value is a color, using web-style syntax, as describe above. Has only one attribute: name - The name used in referring to this color.
Example XML Declaration
The following code declares two colors, the first fully opaque, and the second translucent.
Example Code Use
Example Java code
// Retrieve a color value.int color = getResources.getColor(R.color.opaque_red);
Example XML code
Strings, with optionalsimple formatting, can be stored and retrieved as resources. You can add formatting to your string by using three standard HTML tags: , , and . 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 theContext.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:
Source file format: XML file requiring a declaration, and a root
Resource source file location: res/values/strings.xml (File name is arbitrary.)
Compiled resource datatype: Resource pointer to a Java CharSequence.
Resource reference name:
Java: R.string.some_name
XML: @[package:]string/some_name (where some_name is the name of a specific string)
Syntax
Value is a string, with optional styling tags. Has only one attribute: name - The name used in referring to this 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 useContext.getString() andfromHtml(String) to retreive the resource and then convert it to formatted text.
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
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.
Store your styled text resource as an escaped string, so that the HTML tags in your text resource are not interpreted as if they were XML tags:
In this example the format string has two arguments: %1$d is a decimal number, %2$s is a string.
Make sure any String arguments are properly escaped if they might contain '<' or '&' characters. ThehtmlEncode(String) method will do this: String escapedTitle = TextUtil.htmlEncode(title);
Use String.format() to format the HTML text, then usefromHtml(String) to convert the HTML text into styled text: 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:
px
Pixels - corresponds to actual pixels on the screen.
in
Inches - based on the physical size of the screen.
mm
Millimeters - based on the physical size of the screen.
pt
Points - 1/72 of an inch based on the physical size of the screen.
dp
Density-independent Pixels - an abstract unit that is based on the physical density of the screen. These units are relative to a 160 dpi screen, so one dp is one pixel on a 160 dpi screen. The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion. Note: The compiler accepts both "dip" and "dp", though "dp" is more consistent with "sp".
sp
Scale-independent Pixels - this is like the dp unit, but it is also 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 user's preference.
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 declaration, and a root
Resource source file location: res/values/dimens.xml (File name is arbitrary, but standard practice is to put all dimensions in one file devoted to dimensions.)
Compiled resource datatype: Resource pointer to a dimension.
Resource reference name:
Java: R.dimen.some_name
XML: @[package:]dimen/some_name (where some_name is the name of a specific
Syntax
A valid dimension value. name - The name used in referring to this dimension.
Example XML Declaration
The following code declares several dimension values.
Example Code Use
Example Java code:
float dimen = Resources.getDimen(R.dimen.one_pixel);
Example XML code:
ADrawable is a type of resource that you retrieve withResources.getDrawable() and use to draw to the screen. There are a number of drawable resources that can be created.
Bitmap Files
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
Compiled resource datatype: Resource pointer to aBitmapDrawable.
Resource reference name:
Java: R.drawable.some_file
XML: @[package:]drawable/some_file
For more discussion and examples using drawable resources, see the discussion in2D Graphics.
Color Drawables
You can create aPaintDrawable 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 declaration, and a root
Resource source file location: res/values/colors.xml (File name is arbitrary, but standard practice is to put the PaintDrawable items in the file along with thenumeric color values.)
Compiled resource datatype: Resource pointer to aPaintDrawable.
Resource reference name:
Java: R.drawable.some_name
XML: @[package:]drawable/some_name (where some_name is the name of a specific resource)
Syntax
A validcolor value. name - The name used in referring to this drawable.
Example XML Declaration
The following code declares several color drawables.
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
Android supports a stretchable bitmap image, called aNinePatch 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.
Source file format: PNG — one resource per file
Resource source file location: res/drawable/some_name.9.png (Filename must end in .9.png)
Compiled resource datatype: Resource pointer to aNinePatchDrawable.
Resource reference name:
Java: R.drawable.some_file
XML: @[package:]drawable.some_file
For more information and examples using NinePatch drawables, see the discussion in2D Graphics.
Animation
Tweened Animation
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 declaration
Resource file location: res/anim/some_file.xml
Compiled resource datatype: Resource pointer to anAnimation.
Resource reference name:
Java: R.anim.some_file
XML: @[package:]anim/some_file
Syntax
The file must have a single root element: this will be either a single
Elements and Attributes
A container that can recursively hold itself or other animations. Represents anAnimationSet. You can include as many child elements of the same or different types as you like. Supports the following attribute: shareInterpolator - Whether to share the same Interpolator among all immediate child elements.
A fading animation. Represents anAlphaAnimation. Supports the following attributes: fromAlpha - 0.0 to 1.0, where 0.0 is transparent.
toAlpha - 0.0 to 1.0, where 0.0 is transparent.
A resizing animation. Represents aScaleAnimation. You can specify what is the center point of the image (the pinned center), from which it grows outward (or inward), by specifying pivotX and pivotY. So, for example, if these were 0, 0 (top left corner), all growth would be down and to the right. scale supports the following attributes: fromXScale - Starting X size, where 1.0 is no change.
toXScale - Ending X size, where 1.0 is no change.
fromYScale - Starting Y size, where 1.0 is no change.
toYScale - Ending Y size, where 1.0 is no change.
pivotX - The X coordinate of the pinned center.
pivotY - The Y coordinate of the pinned center.
A vertical/horizontal motion animation. Represents aTranslateAnimation. Supports the following attributes in any of the following three formats: values from -100 to 100, ending with "%", indicating a percentage relative to itself; values from -100 to 100, ending in "%p", indicating a percentage relative to its parent; a float with no suffix, indicating an absolute value. fromXDelta - Starting X location.
toXDelta - Ending X location.
fromYDelta - Starting Y location.
toYDelta - Ending Y location.
A rotation animation. Represents aRotateAnimation. Supports the following attributes: fromDegrees - Starting rotation, in degrees.
toDegrees - Ending rotation, in degrees.
pivotX - The X coordinate of the center of rotation, in pixels, where (0,0) is the top left corner.
pivotY - The Y coordinate of the center of rotation, in pixels, where (0,0) is the top left corner.
You can also use any of the interpolator subclass elements defined inR.styleable. Examples include
In addition to the attributes defined for each element above, the elements
duration
Duration, in milliseconds, for this effect.
startOffset
Offset start time for this effect, in milliseconds.
fillBefore
When set true, the animation transformation is applied before the animation begins.
fillAfter
When set true, the animation transformation is applied after the animation ends.
repeatCount
Defines the number of times the animation should repeat.
repeatMode
Defines the animation behavior when it reaches the end and the repeat count is greater than 0. Options are to either restart or reverse the animation.
zAdjustment
Defines the z-axis ordering mode to use when running the animation (normal, top, or bottom).
interpolator
You can optionally set an interpolator for each element to determine how quickly or slowly it performs its effect over time. For example, slow at the beginning and faster at the end for EaseInInterpolator, and the reverse for EaseOutInterpolator. A list of interpolators is given inR.anim. To specify these, use the syntax @android:anim/interpolatorName.
For more discussion and animation code samples, see the discussion in the2D Graphics document.
Menus
Application menus (Options Menu, Context Menu, or Sub Menu) can be defined as XML resources and inflated by your application usingMenuInflater.
Source file format: XML file, one resource per file, one root tag, declaration not required.
Resource file location: res/menu/some_file.xml
Compiled resource datatype: Resource pointer to aMenu (or subclass) resource.
Resource reference name:
Java: R.menu.some_file
Syntax
The file must have a single root element: a