Merge "cherry-pick from master: Icf079f5f45b1745a8d54f504e28dbbb52c6f7c96 docs: rewrite resources documentation" into froyo

This commit is contained in:
Scott Main
2010-04-09 17:03:55 -07:00
committed by Android (Google) Code Review
19 changed files with 4571 additions and 2299 deletions

View File

@@ -99,18 +99,36 @@
</li>
<li class="toggle-list">
<div><a href="<?cs var:toroot ?>guide/topics/resources/index.html">
<span class="en">Resources and Assets</span>
<span class="en">Application Resources</span>
</a></div>
<ul>
<li><a href="<?cs var:toroot ?>guide/topics/resources/resources-i18n.html">
<span class="en">Resources and I18n</span>
<li><a href="<?cs var:toroot ?>guide/topics/resources/providing-resources.html">
<span class="en">Providing Resources</span>
</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/resources/available-resources.html">
<span class="en">Available Resource Types</span>
<li><a href="<?cs var:toroot ?>guide/topics/resources/accessing-resources.html">
<span class="en">Accessing Resources</span>
</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/resources/runtime-changes.html">
<span class="en">Handling Runtime Changes</span>
</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/resources/localization.html">
<span class="en">Localization</span>
</a></li>
<li class="toggle-list">
<div><a href="<?cs var:toroot ?>guide/topics/resources/available-resources.html">
<span class="en">Resource Types</span>
</a></div>
<ul>
<li><a href="<?cs var:toroot ?>guide/topics/resources/animation-resource.html">Animation</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/resources/color-list-resource.html">Color State List</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/resources/drawable-resource.html">Drawable</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/resources/layout-resource.html">Layout</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/resources/menu-resource.html">Menu</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/resources/string-resource.html">String</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/resources/style-resource.html">Style</a></li>
<li><a href="<?cs var:toroot ?>guide/topics/resources/more-resources.html">More Types</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="<?cs var:toroot ?>guide/topics/intents/intents-filters.html">

View File

@@ -442,7 +442,7 @@ class is the basis for frame animations.</p>
<p>While you can define the frames of an animation in your code, using the
{@link android.graphics.drawable.AnimationDrawable} class API, it's more simply accomplished with a single XML
file that lists the frames that compose the animation. Like the tween animation above, the XML file for this kind
of animation belongs in the <code>res/anim/</code> directory of your Android project. In this case,
of animation belongs in the <code>res/drawable/</code> directory of your Android project. In this case,
the instructions are the order and duration for each frame of the animation.</p>
<p>The XML file consists of an <code>&lt;animation-list></code> element as the root node and a series
@@ -459,7 +459,7 @@ Here's an example XML file for a frame-by-frame animation:</p>
<p>This animation runs for just three frames. By setting the <code>android:oneshot</code> attribute of the
list to <var>true</var>, it will cycle just once then stop and hold on the last frame. If it is set <var>false</var> then
the animation will loop. With this XML saved as <code>rocket_thrust.xml</code> in the <code>res/anim/</code> directory
the animation will loop. With this XML saved as <code>rocket_thrust.xml</code> in the <code>res/drawable/</code> directory
of the project, it can be added as the background image to a View and then called to play. Here's an example Activity,
in which the animation is added to an {@link android.widget.ImageView} and then animated when the screen is touched:</p>
<pre>
@@ -470,7 +470,7 @@ public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.main);
ImageView rocketImage = (ImageView) findViewById(R.id.rocket_image);
rocketImage.setBackgroundResource(R.anim.rocket_thrust);
rocketImage.setBackgroundResource(R.drawable.rocket_thrust);
rocketAnimation = (AnimationDrawable) rocketImage.getBackground();
}

View File

@@ -0,0 +1,284 @@
page.title=Accessing Resources
parent.title=Application Resources
parent.link=index.html
@jd:body
<div id="qv-wrapper">
<div id="qv">
<h2>Quickview</h2>
<ul>
<li>Resources can be referenced from code using integers from {@code R.java}, such as
{@code R.drawable.myimage}</li>
<li>Resources can be referenced from resources using a special XML syntax, such as {@code
&#64;drawable/myimage}</li>
<li>You can also access your app resources with methods in
{@link android.content.res.Resources}</li>
</ul>
<h2>Key classes</h2>
<ol>
<li>{@link android.content.res.Resources}</li>
</ol>
<h2>In this document</h2>
<ol>
<li><a href="#ResourcesInCode">Accessing Resources in Code</a></li>
<li><a href="#ReferencesToResources">Accessing Resources in Other XML Resources</a>
<ol>
<li><a href="#ReferencesToThemeAttributes">Referencing style attributes</a></li>
</ol>
</li>
</ol>
<h2>See also</h2>
<ol>
<li><a href="providing-resources.html">Providing Resources</a></li>
<li><a href="available-resources.html">Resource Types</a></li>
</ol>
</div>
</div>
<p>There are two ways you can reference your resources for use in your application:</p>
<ul>
<li><strong>From your code:</strong> Using an integer from a sub-class in your {@code R} class,
such as:
<p>{@code R.string.hello}</p>
<p>You will see Android APIs that accept this kind of resource identifier as a method parameter
(usually defined as the {@code id} parameter).</p>
</li>
<li><strong>From another resource:</strong> Using a special XML syntax that corresponds to the
{@code R} sub-class, such as:
<p>{@code &#64;string/hello}</p>
<p>You can use this syntax in an XML resource any place where a value is expected that is
matched by the existing resource. For example, if you need to provide a string in either an XML
attribute or element value, you can reference a resource instead of providing a hard-coded
string.</p>
</li>
</ul>
<h2 id="ResourcesInCode">Accessing Resources in Code </h2>
<p>When your application is compiled, Android generates the {@code R.java} file (inside
the {@code gen/} directory), which contains resource
identifiers to all the resources in your {@code res/} directory. For each type of resource, a
specific subclass is added to the {@code R} class (for example,
{@code R.drawable}) and for each resource of that type, a static
integer is added to the subclass (for example,
{@code R.drawable.icon}). This integer is the resource ID and you can use it to retrieve
your resource from your application code.</p>
<div class="sidebox-wrapper">
<div class="sidebox">
<h2>Access to Original Files</h2>
<p>While uncommon, you might need access your original files and directories. If you do, then
saving your files in {@code res/} won't work for you. Instead, you can save your resources in the
{@code assets/} directory.</p>
<p>Files saved in the {@code assets/} directory will <em>not</em> be given a resource
ID, so you can't reference them through the {@code R} class or from XML resources. Instead, you can
query files in the {@code assets/} directory like a normal file system and read raw data using
{@link android.content.res.AssetManager}.</p>
<p>However, if all you require is the ability to read raw data (such as a video or audio file),
then save the file in the {@code res/raw/} directory and read a stream of bytes using {@link
android.content.res.Resources#openRawResource(int)}.</p>
</div>
</div>
<p class="caution"><strong>Caution:</strong> You should never modify the {@code
R.java} file by hand&mdash;it is generated by the {@code aapt} tool when your project is
compiled. Any changes will be overridden next time you compile.</p>
<p>Here is the syntax to reference a resource in code:</p>
<p>
<code>[<em>&lt;package_name&gt;</em>.]R.<em>&lt;resource_type&gt;</em>.<em>&lt;resource_name&gt;</em></code>
</p>
<ul>
<li><em>{@code &lt;package_name&gt;}</em> is the name of the package in which the resource is located (not
required when referencing resources from your own package).</li>
<li><em>{@code &lt;resource_type&gt;}</em> is the {@code R} subclass for the resource type.</li>
<li><em>{@code &lt;resource_name&gt;}</em> is either the {@code
android:name} attribute value (for some resources defined in XML files) or the resource filename
without the extension.</li>
</ul>
<p>See <a href="resource-types.html">Resource Types</a> for
more information about each resource type and how to reference them.</p>
<p>In many cases, you can supply an API method with the resource ID. For example, to set the image
for an {@link android.widget.ImageView}:</p>
<pre>
ImageView iv = (ImageView) findViewById(R.id.myimageview);
iv.setImageResource(R.drawable.myimage);
</pre>
<p>You can also retrieve your
resource objects using methods in {@link android.content.res.Resources}, which you can create an
instance of with {@link android.content.Context#getResources Context.getResources()}. For example,
to get a string:</p>
<pre>
Resources res = this.getResources();
String string = res.getString(R.string.mystring);
</pre>
<p>You can also access resources from the platform by prefixing the {@code android}
namespace. Android contains a number of standard resources, such as styles and themes for your
layout, button backgrounds, and layouts. To refer to these in code, qualify your reference with the
<code>android</code> package name. For example,
<code>android.R.layout.simple_gallery_item</code>.</p>
<p>Here are some examples of using resources in code:</p>
<pre>
// Load a background for the current screen from a drawable resource
{@link android.app.Activity#getWindow()}.{@link
android.view.Window#setBackgroundDrawableResource(int)
setBackgroundDrawableResource}(R.drawable.my_background_image) ;
// Set the Activity title by getting a string from the Resources object, because
// this method requires a CharSequence rather than a resource ID
{@link android.app.Activity#getWindow()}.{@link android.view.Window#setTitle(CharSequence)
setTitle}(getResources().{@link android.content.res.Resources#getText(int)
getText}(R.string.main_title));
// Load a custom layout for the current screen
{@link android.app.Activity#setContentView(int)
setContentView}(R.layout.main_screen);
// Set a slide in animation by getting an Animation from the Resources object
mFlipper.{@link android.widget.ViewAnimator#setInAnimation(Animation)
setInAnimation}(AnimationUtils.loadAnimation(this,
R.anim.hyperspace_in));
// Set the text on a TextView object using a resource ID
TextView msgTextView = (TextView) findViewById(R.id.msg);
msgTextView.{@link android.widget.TextView#setText(int) setText}(R.string.hello_message);
</pre>
<h2 id="ReferencesToResources">Accessing Resources in other XML Resources</h2>
<p>When creating an XML resource, some values for attributes and elements can be a reference to
an existing resource. This is often used in layout files to supply strings and images.</p>
<p>Here is the syntax to reference a resource in an XML resource:</p>
<p><code>@[<em>&lt;package_name&gt;</em>:]<em>&lt;resource_type&gt;</em>/<em>&lt;resource_name&gt;</em></code></p>
<ul>
<li>{@code &lt;package_name&gt;} is the name of the package in which the resource is located (not
required when referencing resources from the same package)</li>
<li>{@code &lt;resource_type&gt;} is the
{@code R} subclass for the resource type</li>
<li>{@code &lt;resource_name&gt;} is either the {@code
android:name} attribute value (for some resources defined in XML files) or the resource filename
without the extension</li>
</ul>
<p>See <a href="resource-types.html">Resource Types</a> for
more information about each resource type and how to reference them.</p>
<p>For example, if you have the following resource file that includes a <a
href="more-resources.html#Color">color resource</a> and a <a
href="string-resource.html">string resource</a>:</p>
<pre>
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;resources>
&lt;color name="opaque_red">#f00&lt;/color>
&lt;string name="hello">Hello!&lt;/string>
&lt;/resources>
</pre>
<p>You can use these resources in the following layout file to set the text color and
text string:</p>
<pre>
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;EditText xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
android:layout_width=&quot;fill_parent&quot;
android:layout_height=&quot;fill_parent&quot;
<strong>android:textColor=&quot;&#64;color/opaque_red&quot;
android:text=&quot;&#64;string/hello&quot;</strong> /&gt;
</pre>
<p>In this case you don't need to specify the package name in the resource reference because the
resources are from your own package. To
reference a system resource, you would need to include the package name. For example:</p>
<pre>
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;EditText xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
android:layout_width=&quot;fill_parent&quot;
android:layout_height=&quot;fill_parent&quot;
<strong>android:textColor=&quot;&#64;android:color/secondary_text_dark&quot;</strong>
android:text=&quot;&#64;string/hello&quot; /&gt;
</pre>
<p class="note"><strong>Note:</strong> You should always use a string resource when supplying
strings in a layout file, as demonstrated above, so that the strings can be localized. For
information about creating alternative resources (such as localized strings), see <a
href="providing-resources.html#AlternativeResources">Providing Alternative
Resources</a>.</p>
<p>This facility for referencing resources between resources can also be used to create
alias resources. For example, you can create new drawable resources that is an alias for an existing
image:</p>
<pre>
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/other_drawable" />
</pre>
<p>This is discussed further in <a href="providing-resources.html#AliasResources">Creating
alias resources</a>.</p>
<h3 id="ReferencesToThemeAttributes">Referencing style attributes</h3>
<p>A style attribute resource is another type of resource that allows you to reference the value
of an attribute in the currently-applied theme. Referencing a style attribute allows you to
customize the look of UI elements by styling them to match standard variations supplied by the
current theme, instead of supplying a hard-coded value. Referencing a style attribute
essentially says, "use the style that is defined by this attribute, in the current theme."</p>
<p>To reference a style attribute, the name syntax is almost identical to the normal resource
format, but instead of the at-symbol ({@code &#64;}), use a question-mark ({@code ?}), and the
resource type portion is optional. For instance:</p>
<p>
<code>
?[<em>&lt;package_name&gt;</em>:][<em>&lt;resource_type&gt;</em>/]<em>&lt;resource_name&gt;</em>
</code>
</p>
<p>For example, here's how you might reference an attribute in a layout,
to set the text color to match the "primary" text color of the system theme:</p>
<pre>
&lt;EditText id=&quot;text&quot;
android:layout_width=&quot;fill_parent&quot;
android:layout_height=&quot;wrap_content&quot;
<strong>android:textColor=&quot;?android:textColorSecondary&quot;</strong>
android:text=&quot;&#64;string/hello_world&quot; /&gt;
</pre>
<p>Using this markup, you are
supplying the name of an attribute resource that will be looked up in the theme.
Because the system resource tool knows that an attribute resource is expected,
you do not need to explicitly state the type (which would be
<code>?android:attr/textColorSecondary</code>), so you can exclude the {@code attr} type.</p>

View File

@@ -0,0 +1,564 @@
page.title=Animation Resources
parent.title=Resource Types
parent.link=available-resources.html
@jd:body
<div id="qv-wrapper">
<div id="qv">
<h2>See also</h2>
<ol>
<li><a href="{@docRoot}guide/topics/graphics/2d-graphics.html#tween-animation">2D
Graphics</a></li>
</ol>
</div>
</div>
<p>An animation resource can define one of two types of animations:</p>
<dl>
<dt><a href="#Tween">Tween Animation</a></dt>
<dd>Creates an animation by performing a series of transformations on a single image.
An {@link android.view.animation.Animation}.</dd>
<dt><a href="#Frame">Frame Animation</a></dt>
<dd>Creates an animation by showing a sequence of images in order.
An {@link android.graphics.drawable.AnimationDrawable}.</dd>
</dl>
<h2 id="Tween">Tween Animation</h2>
<p>An animation defined in XML that performs transitions such as rotating,
fading, moving, and stretching on a graphic.
</p>
<dl class="xml">
<dt>file location:</dt>
<dd><code>res/anim/<em>filename</em>.xml</code><br/>
The filename will be used as the resource ID.</dd>
<dt>compiled resource datatype:</dt>
<dd>Resource pointer to an {@link android.view.animation.Animation}.</dd>
<dt>resource reference:</dt>
<dd>
In Java: <code>R.anim.<em>filename</em></code><br/>
In XML: <code>@[<em>package</em>:]anim/<em>filename</em></code>
</dd>
<dt>syntax:</dt>
<dd>
<pre class="stx">
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;<a href="#set-element">set</a> xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@[package:]anim/<em>interpolator_resource</em>"
android:shareInterpolator=["true" | "false"] &gt;
&lt;<a href="#alpha-element">alpha</a>
android:fromAlpha="<em>float</em>"
android:toAlpha="<em>float</em>" /&gt;
&lt;<a href="#scale-element">scale</a>
android:fromXScale="<em>float</em>"
android:toXScale="<em>float</em>"
android:fromYScale="<em>float</em>"
android:toYScale="<em>float</em>"
android:pivotX="<em>string</em>"
android:pivotY="<em>string</em>" /&gt;
&lt;<a href="#translate-element">translate</a>
android:fromX="<em>string</em>"
android:toX="<em>string</em>"
android:fromY="<em>string</em>"
android:toY="<em>string</em>" /&gt;
&lt;<a href="#rotate-element">rotate</a>
android:fromDegrees="<em>float</em>"
android:toDegrees="<em>float</em>"
android:pivotX="<em>string</em>"
android:pivotY="<em>string</em>" /&gt;
&lt;<a href="#set-element">set</a>&gt;
...
&lt;/set&gt;
&lt;/set&gt;
</pre>
<p>The file must have a single root element: either an
<code>&lt;alpha&gt;</code>, <code>&lt;scale&gt;</code>, <code>&lt;translate&gt;</code>,
<code>&lt;rotate&gt;</code>, or <code>&lt;set&gt;</code> element that holds
a group (or groups) of other animation elements (even nested <code>&lt;set&gt;</code> elements).
</p>
</dd>
<dt>elements:</dt>
<dd>
<dl class="tag-list">
<dt id="set-element"><code>&lt;set&gt;</code></dt>
<dd>A container that holds other animation elements
(<code>&lt;alpha&gt;</code>, <code>&lt;scale&gt;</code>, <code>&lt;translate&gt;</code>,
<code>&lt;rotate&gt;</code>) or other <code>&lt;set&gt;</code> elements. Represents an {@link
android.view.animation.AnimationSet}.
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>android:interpolator</code></dt>
<dd><em>Interpolator resource</em>.
An {@link android.view.animation.Interpolator} to apply on the animation.
The value must be a reference to a resource that specifies an interpolator
(not an interpolator class name). There are default interpolator
resources available from the platform or you can create your own interpolator resource.
See the discussion below for more about <a href="#Interpolators">Interpolators</a>.</dd>
<dt><code>android:shareInterpolator</code></dt>
<dd><em>Boolean</em>. "true" if you want to share the same interpolator among all child
elements.</dd>
</dl>
</dd>
<dt id="alpha-element"><code>&lt;alpha&gt;</code></dt>
<dd>A fade-in or fade-out animation. Represents an {@link
android.view.animation.AlphaAnimation}.
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>android:fromAlpha</code></dt>
<dd><em>Float</em>. Starting opacity offset, where 0.0 is transparent and 1.0
is opaque.</dd>
<dt><code>android:toAlpha</code></dt>
<dd><em>Float</em>. Ending opacity offset, where 0.0 is transparent and 1.0
is opaque.</dd>
</dl>
<p>For more attributes supported by <code>&lt;alpha&gt;</code>, see the
{@link android.view.animation.Animation} class reference (of which, all XML attributes are
inherrited by this element).</p>
</dd>
<dt id="scale-element"><code>&lt;scale&gt;</code></dt>
<dd>A resizing animation. You can specify the center point of the image from which it grows
outward (or inward) by specifying {@code pivotX} and {@code pivotY}. For example, if these values
are 0, 0 (top-left corner), all growth will be down and to the right. Represents a {@link
android.view.animation.ScaleAnimation}.
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>android:fromXScale</code></dt>
<dd><em>Float</em>. Starting X size offset, where 1.0 is no change.</dd>
<dt><code>android:toXScale</code></dt>
<dd><em>Float</em>. Ending X size offset, where 1.0 is no change.</dd>
<dt><code>android:fromYScale</code></dt>
<dd><em>Float</em>. Starting Y size offset, where 1.0 is no change.</dd>
<dt><code>android:toYScale</code></dt>
<dd><em>Float</em>. Ending Y size offset, where 1.0 is no change.</dd>
<dt><code>android:pivotX</code></dt>
<dd><em>Float</em>. The X coordinate to remain fixed when the object is scaled.</dd>
<dt><code>android:pivotY</code></dt>
<dd><em>Float</em>. The Y coordinate to remain fixed when the object is scaled.</dd>
</dl>
<p>For more attributes supported by <code>&lt;scale&gt;</code>, see the
{@link android.view.animation.Animation} class reference (of which, all XML attributes are
inherrited by this element).</p>
</dd>
<dt id="translate-element"><code>&lt;translate&gt;</code></dt>
<dd>A vertical and/or horizontal motion. 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 value with no suffix, indicating an absolute value. Represents a {@link
android.view.animation.TranslateAnimation}.
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>android:fromXDelta</code></dt>
<dd><em>Float or percentage</em>. Starting X offset. Either in: pixels relative to the
normal position, in percentage relative to the element width (%), or relative to the parent width
(%p).</dd>
<dt><code>android:toXDelta</code></dt>
<dd><em>Float or percentage</em>. Ending X offset. Either in: pixels relative to the
normal position, in percentage relative to the element width (%), or relative to the parent width
(%p).</dd>
<dt><code>android:fromYDelta</code></dt>
<dd><em>Float or percentage</em>. Starting Y offset. Either in: pixels relative to the
normal position, in percentage relative to the element height (%), or relative to the parent height
(%p).</dd>
<dt><code>android:toYDelta</code></dt>
<dd><em>Float or percentage</em>. Ending Y offset. Either in: pixels relative to the
normal position, in percentage relative to the element height (%), or relative to the parent height
(%p).</dd>
</dl>
<p>For more attributes supported by <code>&lt;translate&gt;</code>, see the
{@link android.view.animation.Animation} class reference (of which, all XML attributes are
inherrited by this element).</p>
</dd>
<dt id="rotate-element"><code>&lt;rotate&gt;</code></dt>
<dd>A rotation animation. Represents a {@link android.view.animation.RotateAnimation}.
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>android:fromDegrees</code></dt>
<dd><em>Integer</em>. Starting angular position, in degrees.</dd>
<dt><code>android:toDegrees</code></dt>
<dd><em>Integer</em>. Ending angular position, in degrees.</dd>
<dt><code>android:pivotX</code></dt>
<dd><em>Integer or percentage</em>. The X coordinate of the center of rotation, in total
pixels (where 0 is the left edge) or percentage of the screen width.</dd>
<dt><code>android:pivotY</code></dt>
<dd><em>Integer or percentage</em>. The Y coordinate of the center of rotation, in total
pixels (where 0 is the top edge) or percentage of the screen height.</dd>
</dl>
<p>For more attributes supported by <code>&lt;rotate&gt;</code>, see the
{@link android.view.animation.Animation} class reference (of which, all XML attributes are
inherrited by this element).</p>
</dd>
</dl>
</dd> <!-- end elements and attributes -->
<dt>example:</dt>
<dd>
<pp>XML file saved at <code>res/anim/hyperspace_jump.xml</code>:</p>
<pre>
&lt;set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false">
&lt;scale
android:interpolator="@android:anim/accelerate_decelerate_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" />
&lt;set
android:interpolator="@android:anim/accelerate_interpolator"
android:startOffset="700">
&lt;scale
android:fromXScale="1.4"
android:toXScale="0.0"
android:fromYScale="0.6"
android:toYScale="0.0"
android:pivotX="50%"
android:pivotY="50%"
android:duration="400" />
&lt;rotate
android:fromDegrees="0"
android:toDegrees="-45"
android:toYScale="0.0"
android:pivotX="50%"
android:pivotY="50%"
android:duration="400" />
&lt;/set>
&lt;/set>
</pre>
<p>This application code will apply the animation to an {@link android.widget.ImageView} and
start the animation:</p>
<pre>
ImageView image = (ImageView) findViewById(R.id.image);
Animation hyperspaceJump = AnimationUtils.{@link android.view.animation.AnimationUtils#loadAnimation(Context,int) loadAnimation}(this, R.anim.hyperspace_jump);
image.{@link android.view.View#startAnimation(Animation) startAnimation}(hyperspaceJump);
</pre>
</dd> <!-- end example -->
<dt>see also:</dt>
<dd>
<ul>
<li><a href="{@docRoot}guide/topics/graphics/2d-graphics.html#tween-animation">2D
Graphics: Tween Animation</a></li>
</ul>
</dd>
</dl>
<h3 id="Interpolators">Interpolators</h3>
<p>An interpolator is an animation modifier defined in XML that affects the rate of change in an
animation. This allows your existing animation effects to be accelerated, decelerated, repeated,
bounced, etc.</p>
<p>An interpolator is applied to an animation element with the {@code android:interpolator}
attribute, the value of which is a reference to an interpolator resource.</p>
<p>All interpolators available in Android are subclasses of the {@link
android.view.animation.Interpolator} class. For each interpolator class, Android
includes a public resource you can reference in order to apply the interpolator to an animation
using the the {@code android:interpolator} attribute.
The following table specifies the resource to use for each interpolator:</p>
<table>
<tr><th>Interpolator class</th><th>Resource ID</th></tr>
<tr>
<td>{@link android.view.animation.AccelerateDecelerateInterpolator}</td>
<td>{@code @android:anim/accelerate_decelerate_interpolator}</td>
</tr>
<tr>
<td>{@link android.view.animation.AccelerateInterpolator}</td>
<td>{@code @android:anim/accelerate_interpolator}</td>
</tr>
<tr>
<td>{@link android.view.animation.AnticipateInterpolator}</td>
<td>{@code @android:anim/anticipate_interpolator}</td>
</tr>
<tr>
<td>{@link android.view.animation.AnticipateOvershootInterpolator}</td>
<td>{@code @android:anim/anticipate_overshoot_interpolator}</td>
</tr>
<tr>
<td>{@link android.view.animation.BounceInterpolator}</td>
<td>{@code @android:anim/bounce_interpolator}</td>
</tr>
<tr>
<td>{@link android.view.animation.CycleInterpolator}</td>
<td>{@code @android:anim/cycle_interpolator}</td>
</tr>
<tr>
<td>{@link android.view.animation.DecelerateInterpolator}</td>
<td>{@code @android:anim/decelerate_interpolator}</td>
</tr>
<tr>
<td>{@link android.view.animation.LinearInterpolator}</td>
<td>{@code @android:anim/linear_interpolator}</td>
</tr>
<tr>
<td>{@link android.view.animation.OvershootInterpolator}</td>
<td>{@code @android:anim/overshoot_interpolator}</td>
</tr>
</table>
<p>Here's how you can apply one of these with the {@code android:interpolator} attribute:</p>
<pre>
&lt;set android:interpolator="@android:anim/accelerate_interpolator"&gt;
...
&lt;/set&gt;
</pre>
<h4>Custom interpolators</h4>
<p>If you're not satisfied with the interpolators provided by the platform (listed in the
table above), you can create a custom interpolator resource with modified attributes.
For example, you can adjust the rate of
acceleration for the {@link android.view.animation.AnticipateInterpolator}, or adjust the number of
cycles for the {@link android.view.animation.CycleInterpolator}. In order to do so, you need to
create your own interpolator resource in an XML file.
</p>
<dl class="xml">
<dt>file location:</dt>
<dd><code>res/anim/<em>filename</em>.xml</code><br/>
The filename will be used as the resource ID.</dd>
<dt>compiled resource datatype:</dt>
<dd>Resource pointer to the corresponding interpolator object.</dd>
<dt>resource reference:</dt>
<dd>
In XML: <code>@[<em>package</em>:]anim/<em>filename</em></code>
</dd>
<dt>syntax:</dt>
<dd>
<pre class="stx">
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;<em>InterpolatorName</em> xmlns:android="http://schemas.android.com/apk/res/android"
android:<em>attribute_name</em>="<em>value</em>"
/>
</pre>
<p>If you don't apply any attributes, then your interpolator will function exactly the same as
those provided by the platform (listed in the table above).</p>
</dd>
<dt>elements:</dt>
<dd>Notice that each {@link android.view.animation.Interpolator} implementation, when
defined in XML, begins its name in lowercase.</p>
<dl class="tag-list">
<dt><code>&lt;accelerateDecelerateInterpolator&gt;</code></dt>
<dd>The rate of change starts and ends slowly but accelerates through the
middle. <p>No attributes.</p></dd>
<dt><code>&lt;accelerateInterpolator&gt;</code></dt>
<dd>The rate of change starts out slowly, then accelerates.
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>android:factor</code></dt>
<dd><em>Float</em>. The acceleration rate (default is 1).</dd>
</dl>
</dd>
<dt><code>&lt;anticipateInterpolator&gt;</code></dt>
<dd>The change starts backward then flings forward.
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>android:tension</code></dt>
<dd><em>Float</em>. The amount of tension to apply (default is 2).</dd>
</dl>
</dd>
<dt><code>&lt;anticipateOvershootInterpolator&gt;</code></dt>
<dd>The change starts backward, flings forward and overshoots the target value, then
settles at the final value.
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>android:tension</code></dt>
<dd><em>Float</em>. The amount of tension to apply (default is 2).</dd>
<dt><code>android:extraTension</code></dt>
<dd><em>Float</em>. The amount by which to multiply the tension (default is
1.5).</dd>
</dl>
</dd>
<dt><code>&lt;bounceInterpolator&gt;</code></dt>
<dd>The change bounces at the end. <p>No attributes</p></dd>
<dt><code>&lt;cycleInterpolator&gt;</code></dt>
<dd>Repeats the animation for a specified number of cycles. The rate of change follows a
sinusoidal pattern.
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>android:cycles</code></dt>
<dd><em>Integer</em>. The number of cycles (default is 1).</dd>
</dl>
</dd>
<dt><code>&lt;decelerateInterpolator&gt;</code></dt>
<dd>The rate of change starts out quickly, then decelerates.
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>android:factor</code></dt>
<dd><em>Float</em>. The deceleration rate (default is 1).</dd>
</dl>
</dd>
<dt><code>&lt;linearInterpolator&gt;</code></dt>
<dd>The rate of change is constant. <p>No attributes.</p></dd>
<dt><code>&lt;overshootInterpolator&gt;</code></dt>
<dd>The change flings forward and overshoots the last value, then comes back.
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>android:tension</code></dt>
<dd><em>Float</em>. The amount of tension to apply (default is 2).</dd>
</dl>
</dd>
</dl>
<dt>example:</dt>
<dd>
<p>XML file saved at <code>res/anim/my_overshoot_interpolator.xml</code>:</p>
<pre>
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;overshootInterpolator xmlns:android="http://schemas.android.com/apk/res/android"
android:tension="7.0"
/>
</pre>
<p>This animation XML will apply the interpolator:</p>
<pre>
&lt;scale xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@anim/my_overshoot_interpolator"
android:fromXScale="1.0"
android:toXScale="3.0"
android:fromYScale="1.0"
android:toYScale="3.0"
android:pivotX="50%"
android:pivotY="50%"
android:duration="700" />
</pre>
</dd>
</dl>
<h2 id="Frame">Frame Animation</h2>
<p>An animation defined in XML that shows a sequence of images in order (like a film).
</p>
<dl class="xml">
<dt>file location:</dt>
<dd><code>res/drawable/<em>filename</em>.xml</code><br/>
The filename will be used as the resource ID.</dd>
<dt>compiled resource datatype:</dt>
<dd>Resource pointer to an {@link android.graphics.drawable.AnimationDrawable}.</dd>
<dt>resource reference:</dt>
<dd>
In Java: <code>R.drawable.<em>filename</em></code><br/>
In XML: <code>@[<em>package</em>:]drawable.<em>filename</em></code>
</dd>
<dt>syntax:</dt>
<dd>
<pre class="stx">
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;<a href="#animation-list-element">animation-list</a> xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot=["true" | "false"] >
&lt;<a href="#item-element">item</a>
android:drawable="@[package:]drawable/<em>drawable_resource_name</em>"
android:duration="<em>integer</em>" />
&lt;/animation-list>
</pre>
</dd>
<dt>elements:</dt>
<dd>
<dl class="tag-list">
<dt id="animation-list-element"><code>&lt;animation-list&gt;</code></dt>
<dd><strong>Required</strong>. This must be the root element. Contains one or more
<code>&lt;item&gt;</code> elements.
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>android:oneshot</code></dt>
<dd><em>Boolean</em>. "true" if you want to perform the animation once; "false" to loop the
animation.</dd>
</dl>
</dd>
<dt id="item-element"><code>&lt;item&gt;</code></dt>
<dd>A single frame of animation. Must be a child of a <code>&lt;animation-list&gt;</code> element.
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>android:drawable</code></dt>
<dd><em>Drawable resource</em>. The drawable to use for this frame.</dd>
<dt><code>android:duration</code></dt>
<dd><em>Integer</em>. The duration to show this frame, in milliseconds.</dd>
</dl>
</dd>
</dl>
</dd> <!-- end elements and attributes -->
<dt>example:</dt>
<dd>
<dl>
<dt>XML file saved at <code>res/anim/rocket.xml</code>:</dt>
<dd>
<pre>
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false">
&lt;item android:drawable="@drawable/rocket_thrust1" android:duration="200" />
&lt;item android:drawable="@drawable/rocket_thrust2" android:duration="200" />
&lt;item android:drawable="@drawable/rocket_thrust3" android:duration="200" />
&lt;/animation-list>
</pre>
</dd>
<dt>This application code will set the animation as the background for a View,
then play the animation:</dt>
<dd>
<pre>
ImageView rocketImage = (ImageView) findViewById(R.id.rocket_image);
rocketImage.{@link android.view.View#setBackgroundResource(int) setBackgroundResource}(R.drawable.rocket_thrust);
rocketAnimation = (AnimationDrawable) rocketImage.{@link android.view.View#getBackground()};
rocketAnimation.{@link android.graphics.drawable.AnimationDrawable#start()};
</pre>
</dd>
</dl>
</dd> <!-- end example -->
</dl>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,165 @@
page.title=Color State List Resource
parent.title=Resource Types
parent.link=available-resources.html
@jd:body
<div id="qv-wrapper">
<div id="qv">
<h2>See also</h2>
<ol>
<li><a href="more-resources.html#Color">Color (simple value)</a></li>
</ol>
</div>
</div>
<p>A {@link android.content.res.ColorStateList} is an object you can define in XML
that you can apply as a color, but will actually change colors, depending on the state of
the {@link android.view.View} object to which it is applied. For example, a {@link
android.widget.Button} widget can exist in one of several different states (pressed, focused,
or niether) and, using a color state list, you can provide a different color during each state.</p>
<p>You can describe the state list in an XML file. Each color is defined in an {@code
&lt;item>} element inside a single {@code &lt;selector>} element. Each {@code &lt;item>}
uses various attributes to describe the state in which it should be used.</p>
<p>During each state change, the state list is traversed top to bottom and the first item that
matches the current state will be used&mdash;the selection is <em>not</em> based on the "best
match," but simply the first item that meets the minimum criteria of the state.</p>
<p class="note"><strong>Note:</strong> If you want to provide a static color resource, use a
simple <a href="more-resources.html#Color">Color</a> value.</p>
<dl class="xml">
<dt>file location:</dt>
<dd><code>res/color/<em>filename</em>.xml</code><br/>
The filename will be used as the resource ID.</dd>
<dt>compiled resource datatype:</dt>
<dd>Resource pointer to a {@link android.content.res.ColorStateList}.</dd>
<dt>resource reference:</dt>
<dd>
In Java: <code>R.color.<em>filename</em></code><br/>
In XML: <code>@[<em>package</em>:]color/<em>filename</em></code>
</dd>
<dt>syntax:</dt>
<dd>
<pre class="stx">
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;<a href="#selector-element">selector</a> xmlns:android="http://schemas.android.com/apk/res/android" >
&lt;<a href="#item-element">item</a>
android:color="<em>hex_color</em>"
android:state_pressed=["true" | "false"]
android:state_focused=["true" | "false"]
android:state_selected=["true" | "false"]
android:state_active=["true" | "false"]
android:state_checkable=["true" | "false"]
android:state_checked=["true" | "false"]
android:state_enabled=["true" | "false"]
android:state_window_focused=["true" | "false"] />
&lt;/selector>
</pre>
</dd>
<dt>elements:</dt>
<dd>
<dl class="tag-list">
<dt id="selector-element"><code>&lt;selector&gt;</code></dt>
<dd><strong>Required.</strong> This must be the root element. Contains one or more {@code
&lt;item>} elements.
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>xmlns:android</code></dt>
<dd><em>String</em>. <strong>Required.</strong> Defines the XML namespace, which must be
<code>"http://schemas.android.com/apk/res/android"</code>.
</dl>
</dd>
<dt id="item-element"><code>&lt;item&gt;</code></dt>
<dd>Defines a color to use during certain states, as described by its attributes. Must be a
child of a <code>&lt;selector&gt;</code> element.
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>android:color</code></dt>
<dd><em>Hexadeximal color</em>. <strong>Required</strong>. The color is specified with an
RGB value and optional alpha channel.
<p>The value always begins with a pound (#) character and then followed by the
Alpha-Red-Green-Blue information in one of the following formats:</p>
<ul>
<li>#<em>RGB</em></li>
<li>#<em>ARGB</em></li>
<li>#<em>RRGGBB</em></li>
<li>#<em>AARRGGBB</em></li>
</ul></dd>
<dt><code>android:state_pressed</code></dt>
<dd><em>Boolean</em>. "true" if this item should be used when the object is pressed (such as when a button
is touched/clicked); "false" if this item should be used in the default, non-pressed state.</dd>
<dt><code>android:state_focused</code></dt>
<dd><em>Boolean</em>. "true" if this item should be used when the object is focused (such as when a button
is highlighted using the trackball/d-pad); "false" if this item should be used in the default,
non-focused state.</dd>
<dt><code>android:state_selected</code></dt>
<dd><em>Boolean</em>. "true" if this item should be used when the object is selected (such as when a
tab is opened); "false" if this item should be used when the object is not selected.</dd>
<dt><code>android:state_checkable</code></dt>
<dd><em>Boolean</em>. "true" if this item should be used when the object is checkable; "false" if this
item should be used when the object is not checkable. (Only useful if the object can
transition between a checkable and non-checkable widget.)</dd>
<dt><code>android:state_checked</code></dt>
<dd><em>Boolean</em>. "true" if this item should be used when the object is checked; "false" if it
should be used when the object is un-checked.</dd>
<dt><code>android:state_enabled</code></dt>
<dd><em>Boolean</em>. "true" if this item should be used when the object is enabled (capable of
receiving touch/click events); "false" if it should be used when the object is disabled.</dd>
<dt><code>android:state_window_focused</code></dt>
<dd><em>Boolean</em>. "true" if this item should be used when the application window has focus (the
application is in the foreground), "false" if this item should be used when the application
window does not have focus (for example, if the notification shade is pulled down or a dialog appears).</dd>
</dl>
<p class="note"><strong>Note:</strong> Remember that the first item in the state list that
matches the current state of the object will be applied. So if the first item in the list contains
none of the state attributes above, then it will be applied every time, which is why your
default value should always be last (as demonstrated in the following example).</p>
</dd>
</dl>
</dd> <!-- end elements and attributes -->
<dt>example:</dt>
<dd>XML file saved at <code>res/color/button_text.xml</code>:
<pre>
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;selector xmlns:android="http://schemas.android.com/apk/res/android">
&lt;item android:state_pressed="true"
android:color="#ffff0000"/> &lt;!-- pressed --&gt;
&lt;item android:state_focused="true"
android:color="#ff0000ff"/> &lt;!-- focused --&gt;
&lt;item android:color="#ff000000"/> &lt;!-- default --&gt;
&lt;/selector>
</pre>
<p>This layout XML will apply the color list to a View:</p>
<pre>
&lt;Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/button_text"
android:textColor="@color/button_text" />
</pre>
</dd> <!-- end example -->
<dt>see also:</dt>
<dd>
<ul>
<li><a href="more-resources.html#Color">Color (simple value)</a></li>
<li>{@link android.content.res.ColorStateList}</li>
<li><a href="drawable-resource.html#StateList">State List Drawable</a></li>
</ul>
</dd>
</dl>

View File

@@ -0,0 +1,711 @@
page.title=Drawable Resources
parent.title=Resource Types
parent.link=available-resources.html
@jd:body
<div id="qv-wrapper">
<div id="qv">
<h2>See also</h2>
<ol>
<li><a href="{@docRoot}guide/topics/graphics/2d-graphics.html">2D Graphics</a></li>
</ol>
</div>
</div>
<p>A drawable resource is a general concept for a graphic that you
can retrieve with {@link android.content.res.Resources#getDrawable(int)}
and draw on the screen. There are several different types of drawables:</p>
<dl>
<dt><a href="#Bitmap">Bitmap File</a><dt>
<dd>A bitmap graphic file ({@code .png}, {@code .jpg}, or {@code .gif}).
A {@link android.graphics.drawable.BitmapDrawable}.</dd>
<dt><a href="#NinePatch">Nine-Patch File</a></dt>
<dd>A PNG file with stretchable regions to allow image resizing based on content ({@code
.9.png}). A {@link android.graphics.drawable.NinePatchDrawable}.</dd>
<!-- <dt><a href="#BitmapAlias">Bitmap Alias</a><dt>
<dd>An alias for a drawable.</dd> -->
<dt><a href="#StateList">State List</a></dt>
<dd>An XML file that references different bitmap graphics
for different states (for example, to use a different image when a button is pressed).
A {@link android.graphics.drawable.StateListDrawable}.</dd>
<dt><a href="#Color">Color</a></dt>
<dd>A resource defined in XML that specifies a rectangle of color, with
optionally rounded corners. A {@link android.graphics.drawable.PaintDrawable}.</dd>
<dt><a href="#Shape">Shape</a></dt>
<dd>An XML file that defines a geometric shape, including colors and gradients.
A {@link android.graphics.drawable.ShapeDrawable}.</dd>
</dl>
<p>Documentation for the {@link android.graphics.drawable.AnimationDrawable} resource
is in the <a href="animation-resource.html">Animation Resource</a> document.</p>
<h2 id="Bitmap">Bitmap File</h2>
<p>A basic bitmap image. Android supports basic bitmap files in a few different formats:
{@code .png} (preferred), {@code .jpg} (acceptable), {@code .gif} (discouraged).</p>
<p class="note"><strong>Note:</strong> Bitmap files may be automatically optimized with lossless
image compression by the <a href="{@docRoot}guide/developing/tools/aapt.html">aapt</a> tool. For
example, a true-color PNG that does not require more than 256 colors may be converted to an 8-bit
PNG with a color palette. This will result in an image of equal quality but which requires less
memory. So be aware that the image binaries placed in this directory can change during the build. If
you plan on reading an image as a bit stream in order to convert it to a bitmap, put your images in
the <code>res/raw/</code> folder instead, where they will not be optimized.</p>
<dl class="xml">
<dt>file location:</dt>
<dd><code>res/drawable/<em>filename</em>.png</code> ({@code .png}, {@code .jpg}, or {@code .gif})<br/>
The filename will be used as the resource ID.</dd>
<dt>compiled resource datatype:</dt>
<dd>Resource pointer to a {@link android.graphics.drawable.BitmapDrawable}.</dd>
<dt>resource reference:</dt>
<dd>
In Java: <code>R.drawable.<em>filename</em></code></li><br/>
In XML: <code>@[<em>package</em>:]drawable/<em>filename</em></code>
</dd>
<dt>example:</dt>
<dd>With an image saved at <code>res/drawable/myimage.png</code>, this layout XML will apply
the image to a View:
<pre>
&lt;ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
<strong>android:src="@drawable/myimage"</strong> />
</pre>
<p>This application code will retrieve the image as a {@link
android.graphics.drawable.Drawable}:</p>
<pre>
Resources res = {@link android.content.Context#getResources()};
Drawable drawable = res.{@link android.content.res.Resources#getDrawable(int) getDrawable}(R.drawable.myimage);
</pre>
</dd>
<dt>see also:</dt>
<dd>
<ul>
<li><a href="{@docRoot}guide/topics/graphics/2d-graphics.html">2D Graphics</a></li>
<li>{@link android.graphics.drawable.BitmapDrawable}</li>
</ul>
</dd>
</dl>
<h2 id="NinePatch">Nine-Patch File</h2>
<p>A {@link android.graphics.NinePatch} is a PNG image in which you can define stretchable regions
that Android will scale when content within the View exceeds the normal image bounds. You will
typically assign this type of image as the background of a View that has at least one dimension set
to {@code "wrap_content"}, and when the View grows to accomodate the content, the Nine-Patch image
will also be scaled to match the size of the View. An example use of a Nine-Patch image is the
background used by Android's standard {@link android.widget.Button} widget, which must stretch to
accommodate the text (or image) inside the button.</p>
<p>For a complete discussion about how to define a Nine-Patch file with stretchable regions,
see the <a href="{@docRoot}guide/topics/graphics/2d-graphics.html#nine-patch">2D Graphics</a>
document.</p>
<dl class="xml">
<dt>file location:</dt>
<dd><code>res/drawable/<em>filename</em>.9.png</code><br/>
The filename will be used as the resource ID.</dd>
<dt>compiled resource datatype:</dt>
<dd>Resource pointer to a {@link android.graphics.drawable.NinePatchDrawable}.</dd>
<dt>resource reference:</dt>
<dd>
In Java: <code>R.drawable.<em>filename</em></code><br/>
In XML: <code>@[<em>package</em>:]drawable/<em>filename</em></code>
</dd>
<dt>example:</dt>
<dd>With an image saved at <code>res/drawable/myninepatch.9.png</code>, this layout XML will
apply the Nine-Patch to a View:
<pre>
&lt;Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
<strong>android:background="@drawable/myninepatch"</strong> />
</pre>
</dd>
<dt>see also:</dt>
<dd>
<ul>
<li><a href="{@docRoot}guide/topics/graphics/2d-graphics.html#nine-patch">2D Graphics</a></li>
<li>{@link android.graphics.drawable.NinePatchDrawable}</li>
</ul>
</dd>
</dl>
<h2 id="StateList">State List</h2>
<p>A {@link android.graphics.drawable.StateListDrawable} is a drawable object defined in XML
that uses a several different images to represent the same graphic, depending on the state of
the object. For example, a {@link
android.widget.Button} widget can exist in one of several different states (pressed, focused,
or niether) and, using a state list drawable, you can provide a different button image for each
state.</p>
<p>You can describe the state list in an XML file. Each graphic is represented by an {@code
&lt;item>} element inside a single {@code &lt;selector>} element. Each {@code &lt;item>}
uses various attributes to describe the state in which it should be used as the graphic for the
drawable.</p>
<p>During each state change, the state list is traversed top to bottom and the first item that
matches the current state will be used&mdash;the selection is <em>not</em> based on the "best
match," but simply the first item that meets the minimum criteria of the state.</p>
<dl class="xml">
<dt>file location:</dt>
<dd><code>res/drawable/<em>filename</em>.xml</code><br/>
The filename will be used as the resource ID.</dd>
<dt>compiled resource datatype:</dt>
<dd>Resource pointer to a {@link android.graphics.drawable.StateListDrawable}.</dd>
<dt>resource reference:</dt>
<dd>
In Java: <code>R.drawable.<em>filename</em></code><br/>
In XML: <code>@[<em>package</em>:]drawable/<em>filename</em></code>
</dd>
<dt>syntax:</dt>
<dd>
<pre class="stx">
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;<a href="#selector-element">selector</a> xmlns:android="http://schemas.android.com/apk/res/android"
android:constantSize=["true" | "false"]
android:dither=["true" | "false"]
android:variablePadding=["true" | "false"] >
&lt;<a href="#item-element">item</a>
android:drawable="@[package:]drawable/<em>drawable_resource</em>"
android:state_pressed=["true" | "false"]
android:state_focused=["true" | "false"]
android:state_selected=["true" | "false"]
android:state_active=["true" | "false"]
android:state_checkable=["true" | "false"]
android:state_checked=["true" | "false"]
android:state_enabled=["true" | "false"]
android:state_window_focused=["true" | "false"] />
&lt;/selector>
</pre>
</dd>
<dt>elements:</dt>
<dd>
<dl class="tag-list">
<dt id="selector-element"><code>&lt;selector&gt;</code></dt>
<dd><strong>Required.</strong> This must be the root element. Contains one or more {@code
&lt;item>} elements.
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>xmlns:android</code></dt>
<dd><em>String</em>. <strong>Required.</strong> Defines the XML namespace, which must be
<code>"http://schemas.android.com/apk/res/android"</code>.
<dt><code>android:constantSize</code></dt>
<dd><em>Boolean</em>. "true" if the drawable's reported internal size will remain constant as the state
changes (the size will be the maximum of all of the states); "false" if the size will vary based on
the current state. Default is false.</dd>
<dt><code>android:dither</code></dt>
<dd><em>Boolean</em>. "true" to enable dithering of the bitmap if the bitmap does not have the same pixel
configuration as the screen (for instance, an ARGB 8888 bitmap with an RGB 565 screen); "false" to
disable dithering. Default is true.</dd>
<dt><code>android:variablePadding</code></dt>
<dd><em>Boolean</em>. "true" if the drawable's padding should change based on the current
state that is selected; "false" if the padding should stay the same (based on the maximum
padding of all the states). Enabling this feature requires that you deal with
performing layout when the state changes, which is often not supported. Default is false.</dd>
</dl>
</dd>
<dt id="item-element"><code>&lt;item&gt;</code></dt>
<dd>Defines a drawable to use during certain states, as described by its attributes. Must be a
child of a <code>&lt;selector&gt;</code> element.
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>android:drawable</code></dt>
<dd><em>Drawable resource</em>. <strong>Required</strong>. Reference to a drawable resource.</dd>
<dt><code>android:state_pressed</code></dt>
<dd><em>Boolean</em>. "true" if this item should be used when the object is pressed (such as when a button
is touched/clicked); "false" if this item should be used in the default, non-pressed state.</dd>
<dt><code>android:state_focused</code></dt>
<dd><em>Boolean</em>. "true" if this item should be used when the object is focused (such as when a button
is highlighted using the trackball/d-pad); "false" if this item should be used in the default,
non-focused state.</dd>
<dt><code>android:state_selected</code></dt>
<dd><em>Boolean</em>. "true" if this item should be used when the object is selected (such as when a
tab is opened); "false" if this item should be used when the object is not selected.</dd>
<dt><code>android:state_checkable</code></dt>
<dd><em>Boolean</em>. "true" if this item should be used when the object is checkable; "false" if this
item should be used when the object is not checkable. (Only useful if the object can
transition between a checkable and non-checkable widget.)</dd>
<dt><code>android:state_checked</code></dt>
<dd><em>Boolean</em>. "true" if this item should be used when the object is checked; "false" if it
should be used when the object is un-checked.</dd>
<dt><code>android:state_enabled</code></dt>
<dd><em>Boolean</em>. "true" if this item should be used when the object is enabled (capable of
receiving touch/click events); "false" if it should be used when the object is disabled.</dd>
<dt><code>android:state_window_focused</code></dt>
<dd><em>Boolean</em>. "true" if this item should be used when the application window has focus (the
application is in the foreground), "false" if this item should be used when the application
window does not have focus (for example, if the notification shade is pulled down or a dialog appears).</dd>
</dl>
<p class="note"><strong>Note:</strong>Remember that the first item in the state list that
matches the current state of the object will be applied. So if the first item in the list contains
none of the state attributes above, then it will be applied every time, which is why your
default value should always be last (as demonstrated in the following example).</p>
</dd>
</dl>
</dd> <!-- end elements and attributes -->
<dt>example:</dt>
<dd>XML file saved at <code>res/drawable/button.xml</code>:
<pre>
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;selector xmlns:android="http://schemas.android.com/apk/res/android">
&lt;item android:state_pressed="true"
android:drawable="@drawable/button_pressed" /> &lt;!-- pressed --&gt;
&lt;item android:state_focused="true"
android:drawable="@drawable/button_focused" /> &lt;!-- focused --&gt;
&lt;item android:drawable="@drawable/button_normal" /> &lt;!-- default --&gt;
&lt;/selector>
</pre>
<p>This layout XML will apply the drawable to a View:</p>
<pre>
&lt;ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
<strong>android:src="@drawable/button"</strong> />
</pre>
</dd> <!-- end example -->
<dt>see also:</dt>
<dd>
<ul>
<li>{@link android.graphics.drawable.StateListDrawable}</li>
</ul>
</dd>
</dl>
<h2 id="Color">Color</h2>
<p>This is a color defined in XML that's used as a drawable to fill a rectangular space,
with optionally rounded corners. This kind of drawable behaves like a color fill.</p>
<p class="note"><strong>Note:</strong> A color drawable is a simple resource that is referenced
using the value provided in the {@code name} attribute (not the name of the XML file). As
such, you can combine a color drawable resources with other simple resources in the one XML file,
under one {@code &lt;resources>} element.</p>
<dl class="xml">
<dt>file location:</dt>
<dd><code>res/drawable/<em>filename</em>.png</code><br/>
The filename is arbitrary. The element's {@code name} will be used as the resource ID.</dd>
<dt>compiled resource datatype:</dt>
<dd>Resource pointer to a {@link android.graphics.drawable.PaintDrawable}.</dd>
<dt>resource reference:</dt>
<dd>
In Java: <code>R.drawable.<em>color_name</em></code><br/>
In XML: <code>@[<em>package</em>:]drawable/<em>color_name</em></code>
</dd>
<dt>syntax:</dt>
<dd>
<pre class="stx">
&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;<a href="#color-resources-element">resources</a>>
&lt;<a href="#drawable-element">drawable</a>
name="<em>color_name</em>"
&gt;<em>color</em>&lt;/drawable&gt;
&lt;/resources&gt;
</pre>
</dd>
<dt>elements:</dt>
<dd>
<dl class="tag-list">
<dt id="color-resources-element"><code>&lt;resources&gt;</code></dt>
<dd><strong>Required.</strong> This must be the root node.
<p>No attributes.</p>
</dd>
<dt id="drawable-element"><code>&lt;drawable&gt;</code></dt>
<dd>A color to use as a drawable rectangle. The value can be
any valid hexadecimal color value or a <a href="more-resources.html#Color">color
resource</a>. A color value always begins with a pound (#) character, followed
by the Alpha-Red-Green-Blue information in one of the following formats:
#<em>RGB</em>, #<em>RRGGBB</em>, #<em>ARGB</em>, or #<em>AARRGGBB</em>.
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>name</code></dt>
<dd><em>String</em>. <strong>Required</strong>.
A name for the color. This name will be used as the resource ID.</dd>
</dl>
</dd>
</dl>
</dd> <!-- end elements and attributes -->
<dt>example:</dt>
<dd>XML file saved at <code>res/drawable/colors.xml</code>:
<pre>
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;resources>
&lt;drawable name="solid_red">#f00&lt;/drawable>
&lt;drawable name="solid_blue">#0000ff&lt;/drawable>
&lt;/resources>
</pre>
<p>This layout XML will apply a color drawable to a View:</p>
<pre>
&lt;TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
<strong>android:background="@drawable/solid_blue"</strong> />
</pre>
<p>This application code will get a color drawable and apply it to a View:</p>
<pre>
Resources res = {@link android.content.Context#getResources()};
Drawable redDrawable = res.{@link android.content.res.Resources#getDrawable(int) getDrawable}(R.drawable.solid_red);
TextView tv = (TextView) findViewByID(R.id.text);
tv.setBackground(redDrawable);
</pre>
</dd> <!-- end example -->
<dt>see also:</dt>
<dd>
<ul>
<li>{@link android.graphics.drawable.PaintDrawable}</li>
</ul>
</dd>
</dl>
<h2 id="Shape">Shape</h2>
<p>This is a generic shape defined in XML.</p>
<dl class="xml">
<dt>file location:</dt>
<dd><code>res/drawable/<em>filename</em>.xml</code><br/>
The filename will be used as the resource ID.</dd>
<dt>compiled resource datatype:</dt>
<dd>Resource pointer to a {@link android.graphics.drawable.ShapeDrawable}.</dd>
<dt>resource reference:</dt>
<dd>
In Java: <code>R.drawable.<em>filename</em></code><br/>
In XML: <code>@[<em>package</em>:]drawable/<em>filename</em></code>
</dd>
<dt>syntax:</dt>
<dd>
<pre class="stx">
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;<a href="#shape-element">shape</a> xmlns:android="http://schemas.android.com/apk/res/android"
android:shape=["rectangle" | "oval" | "line" | "ring"] >
&lt;<a href="#gradient-element">gradient</a>
android:angle="<em>integer</em>"
android:centerX="<em>integer</em>"
android:centerY="<em>integer</em>"
android:centerColor="<em>integer</em>"
android:gradientRadius="<em>integer</em>"
android:type=""
android:usesLevel=""
android:startColor="<em>color</em>"
android:endColor="<em>color</em>" />
&lt;<a href="#solid-element">solid</a>
android:color="<em>color</em>" />
&lt;<a href="#stroke-element">stroke</a>
android:width="<em>integer</em>"
android:color="<em>color</em>"
android:dashWidth="<em>integer</em>"
android:dashGap="<em>integer</em>" />
&lt;<a href="#padding-element">padding</a>
android:left="<em>integer</em>"
android:top="<em>integer</em>"
android:right="<em>integer</em>"
android:bottom="<em>integer</em>" />
&lt;<a href="#corners-element">corners</a>
android:radius="<em>integer</em>"
android:topLeftRadius="<em>integer</em>"
android:topRightRadius="<em>integer</em>"
android:bottomLeftRadius="<em>integer</em>"
android:bottomRightRadius="<em>integer</em>" />
&lt;/shape>
</pre>
</dd>
<dt>elements:</dt>
<dd>
<dl class="tag-list">
<dt id="shape-element"><code>&lt;shape&gt;</code></dt>
<dd><strong>Required.</strong> This must be the root element.
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>android:shape</code></dt>
<dd><em>Keyword</em>. Defines the type of shape. Valid values are:
<table>
<tr><th>Value</th><th>Desciption</th></tr>
<tr><td>{@code "rectangle"}</td>
<td>A rectangle that fills the containing View. This is the default shape.</td></tr>
<tr><td>{@code "oval"}</td>
<td>An oval shape that fits the dimensions of the containing View.</td></tr>
<tr><td>{@code "line"}</td>
<td>A horizontal line that spans the width of the containing View. This
shape requires the {@code &lt;stroke>} element to define the width of the
line.</td></tr>
<tr><td>{@code "ring"}</td>
<td>A ring shape.</td></tr>
</table>
</dd>
</dl>
<p>The following attributes are used only when {@code android:shape="ring"}:</p>
<dl class="atn-list">
<dt><code>android:innerRadius</code></dt>
<dd><em>Dimension</em>. The radius for the
inner part of the ring (the hole in the middle), as a dimension value or <a
href="more-resources.html#Dimension">dimension resource</a>.</dd>
<dt><code>android:innerRadiusRatio</code></dt>
<dd><em>Float</em>. The radius for the inner
part of the ring, expressed as a ratio of the ring's width. For instance, if {@code
android:innerRadiusRatio="5"}, then the inner radius equals the ring's width divided by 5. This
value will be overridden by {@code android:innerRadius}. Default value is 9.</dd>
<dt><code>android:thickness</code></dt>
<dd><em>Dimension</em>. The thickness of the
ring, as a dimension value or <a
href="more-resources.html#Dimension">dimension resource</a>.</dd>
<dt><code>android:thicknessRatio</code></dt>
<dd><em>Float</em>. The thickness of the ring,
expressed as a ratio of the ring's width. For instance, if {@code android:thicknessRatio="2"}, then
the thickness equals the ring's width divided by 2. This value will be overridden by {@code
android:innerRadius}. Default value is 3.</dd>
<dt><code>android:useLevel</code></dt>
<dd><em>Boolean</em>. "true" if this is used as
a {@link android.graphics.drawable.LevelListDrawable}. This should normally be "false"
or your shape may not appear.</dd>
</dl>
<dt id="gradient-element"><code>&lt;gradient&gt;</code></dt>
<dd>Specifies a gradient color for the shape.
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>android:type</code></dt>
<dd><em>Keyword</em>. The type of gradient pattern to apply. Valid values are:
<table>
<tr><th>Value</th><th>Description</th></tr>
<tr><td>{@code "linear"}</td>
<td>A linear gradient. This is the default.</td></tr>
<tr><td>{@code "radial"}</td>
<td>A radial gradient. The start color is the center color.</td></tr>
<tr><td>{@code "sweep"}</td>
<td>A sweeping line gradient. </td></tr>
</table>
</dd>
<dt><code>android:angle</code></dt>
<dd><em>Integer</em>. The angle for the gradient, in degrees. 0 is left to right, 90 is
bottom to top. It must be a multiple of 45. Default is 0.</dd>
<dt><code>android:centerX</code></dt>
<dd><em>Float</em>. The relative X-position for the center of the gradient (0 - 1.0).
Does not apply when {@code android:type="linear"}.</dd>
<dt><code>android:centerY</code></dt>
<dd><em>Float</em>. The relative Y-position for the center of the gradient (0 - 1.0).
Does not apply when {@code android:type="linear"}.</dd>
<dt><code>android:centerColor</code></dt>
<dd><em>Color</em>. Optional color that comes between the start and end colors, as a
hexadecimal value or <a href="more-resources.html#Color">color resource</a>.</dd>
<dt><code>android:gradientRadius</code></dt>
<dd><em>Float</em>. The radius for the gradient. Only applied when {@code
android:type="radial"}.</dd>
<dt><code>android:useLevel</code></dt>
<dd><em>Boolean</em>. "true" if this is used as a {@link
android.graphics.drawable.LevelListDrawable}.</dd>
<dt><code>android:startColor</code></dt>
<dd><em>Color</em>. The starting color, as a hexadecimal
value or <a href="more-resources.html#Color">color resource</a>.</dd>
<dt><code>android:endColor</code></dt>
<dd><em>Color</em>. The ending color, as a hexadecimal
value or <a href="more-resources.html#Color">color resource</a>.</dd>
</dl>
</dd>
<dt id="solid-element"><code>&lt;solid&gt;</code></dt>
<dd>A solid color to fill the shape.
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>android:color</code></dt>
<dd><em>Color</em>. The color to apply to the shape, as a hexadecimal
value or <a href="more-resources.html#Color">color resource</a>.</dd>
</dl>
</dd>
<dt id="stroke-element"><code>&lt;stroke&gt;</code></dt>
<dd>A stroke line for the shape.
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>android:width</code></dt>
<dd><em>Dimension</em>. The thickness of the line, as a dimension value or <a
href="more-resources.html#Dimension">dimension resource</a>.</dd>
<dt><code>android:color</code></dt>
<dd><em>Color</em>. The color of the line, as a
hexadecimal value or <a href="more-resources.html#Color">color resource</a>.</dd>
<dt><code>android:dashGap</code></dt>
<dd><em>Dimension</em>. The distance between line dashes, as a dimension value or <a
href="more-resources.html#Dimension">dimension resource</a>. Only valid if {@code
android:dashWidth} is set.</dd>
<dt><code>android:dashWidth</code></dt>
<dd><em>Dimension</em>. The size of each dash line, as a dimension value or <a
href="more-resources.html#Dimension">dimension resource</a>. Only valid if {@code
android:dashGap} is set.</dd>
</dl>
</dd>
<dt id="padding-element"><code>&lt;padding&gt;</code></dt>
<dd>Padding to apply to the containing View element (this pads the position of the View
content, not the shape).
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>android:left</code></dt>
<dd><em>Dimension</em>. Left padding, as a dimension value or <a
href="more-resources.html#Dimension">dimension resource</a>.</dd>
<dt><code>android:top</code></dt>
<dd><em>Dimension</em>. Top padding, as a dimension value or <a
href="more-resources.html#Dimension">dimension resource</a>.</dd>
<dt><code>android:right</code></dt>
<dd><em>Dimension</em>. Right padding, as a dimension value or <a
href="more-resources.html#Dimension">dimension resource</a>.</dd>
<dt><code>android:bottom</code></dt>
<dd><em>Dimension</em>. Bottom padding, as a dimension value or <a
href="more-resources.html#Dimension">dimension resource</a>.</dd>
</dl>
</dd>
<dt id="corners-element"><code>&lt;corners&gt;</code></dt>
<dd>Creates rounded corners for the shape. Applies only when the shape is a rectangle.
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>android:radius</code></dt>
<dd><em>Dimension</em>. The radius for all corners, as a dimension value or <a
href="more-resources.html#Dimension">dimension resource</a>. This will be overridden for each
corner by the following attributes.</dd>
<dt><code>android:topLeftRadius</code></dt>
<dd><em>Dimension</em>. The radius for the top-left corner, as a dimension value or <a
href="more-resources.html#Dimension">dimension resource</a>.</dd>
<dt><code>android:topRightRadius</code></dt>
<dd><em>Dimension</em>. The radius for the top-right corner, as a dimension value or <a
href="more-resources.html#Dimension">dimension resource</a>.</dd>
<dt><code>android:bottomLeftRadius</code></dt>
<dd><em>Dimension</em>. The radius for the bottom-left corner, as a dimension value or <a
href="more-resources.html#Dimension">dimension resource</a>.</dd>
<dt><code>android:bottomRightRadius</code></dt>
<dd><em>Dimension</em>. The radius for the bottom-right corner, as a dimension value or <a
href="more-resources.html#Dimension">dimension resource</a>.</dd>
</dl>
<p class="note"><strong>Note:</strong> Every corner must (initially) be provided a corner
radius greater than zero, or else no corners will be rounded. If you want specific corners
to <em>not</em> be rounded, a work-around is to use {@code android:radius} to set a default corner
radius greater than zero, but then override each and every corner with the values you really
want, providing zero ("0dp") where you don't want rounded corners.</p>
</dd>
</dl>
</dd> <!-- end elements and attributes -->
<dt>example:</dt>
<dd>XML file saved at <code>res/drawable/gradient_box.xml</code>:
<pre>
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
&lt;gradient
android:startColor="#FFFF0000"
android:endColor="#80FF00FF"
android:angle="45"/>
&lt;padding android:left="7dp"
android:top="7dp"
android:right="7dp"
android:bottom="7dp" />
&lt;corners android:radius="8dp" />
&lt;/shape>
</pre>
<p>This layout XML will apply the shape drawable to a View:</p>
<pre>
&lt;TextView
android:background="@drawable/gradient_box"
android:layout_height="wrap_content"
android:layout_width="wrap_content" />
</pre>
<p>This application code will get the shape drawable and apply it to a View:</p>
<pre>
Resources res = {@link android.content.Context#getResources()};
Drawable shape = res. {@link android.content.res.Resources#getDrawable(int) getDrawable}(R.drawable.gradient_box);
TextView tv = (TextView)findViewByID(R.id.textview);
tv.setBackground(shape);
</pre>
</dd> <!-- end example -->
</dl>

View File

@@ -1,40 +1,104 @@
page.title=Resources and Assets
page.title=Application Resources
@jd:body
<div id="qv-wrapper">
<div id="qv">
<h2>Key classes</h2>
<h2>Topics</h2>
<ol>
<li>{@link android.content.res.Resources}</li>
<li>{@link android.content.res.AssetManager}</li>
<li><a href="providing-resources.html">Providing Resources</a></li>
<li><a href="accessing-resources.html">Accessing Resources</a></li>
<li><a href="runtime-changes.html">Handling Runtime Changes</a></li>
<li><a href="localization.html">Localization</a></li>
</ol>
<h2>Reference</h2>
<ol>
<li><a href="available-resources.html">Resource Types</a></li>
</ol>
</div>
</div>
<p>Resources are an integral part of an Android application.
In general, these are external elements that you want to include and reference within your application,
like images, audio, video, text strings, layouts, themes, etc. Every Android application contains
a directory for resources (<code>res/</code>) and a directory for assets (<code>assets/</code>).
Assets are used less often, because their applications are far fewer. You only need to save data
as an asset when you need to read the raw bytes. The directories for resources and assets both
reside at the top of an Android project tree, at the same level as your source code directory
(<code>src/</code>).</p>
<p>The difference between "resources" and "assets" isn't much on the surface, but in general,
you'll use resources to store your external content much more often than you'll use assets.
The real difference is that anything
placed in the resources directory will be easily accessible from your application from the
<code>R</code> class, which is compiled by Android. Whereas, anything placed in the assets
directory will maintain its raw file format and, in order to read it, you must use the
{@link android.content.res.AssetManager} to read the file as a stream of bytes. So keeping
files and data in resources (<code>res/</code>) makes them easily accessible.</p>
<p>You should always externalize resources such as images and strings from your application
code, so that you can maintain them independently. Externalizing your
resources also allows you to provide alternative resources that support specific device
configurations such as different languages or screen sizes, which becomes increasingly
important as more Android-powered devices become available with different configurations. In order
to provide this functionality, you must organize resources in your project's {@code res/}
directory, using various sub-directories that group resources by type and configuration.</p>
<p>Within the documents of this topic, you'll find information on the kinds of standard resources
that are typically used in an Android application and how to reference them from you code.
<a href="{@docRoot}guide/topics/resources/resources-i18n.html">Resources and Internationalization</a>
is where you should start, to learn more about how Android utilizes project resources. Then, the
<a href="{@docRoot}guide/topics/resources/available-resources.html">Available Resource Types</a>
document offers a summary of various resource types and a reference to their specifications.
</p>
<div class="figure" style="width:441px">
<img src="{@docRoot}images/resources/resource_devices_diagram1.png" height="137" alt="" />
<p class="img-caption">
<strong>Figure 1.</strong> Two device configurations, both using default
resources.</p>
</div>
<div class="figure" style="width:441px">
<img src="{@docRoot}images/resources/resource_devices_diagram2.png" height="137" alt="" />
<p class="img-caption">
<strong>Figure 2.</strong> Two device configurations, one using alternative
resources.</p>
</div>
<p>For any type of resource, you can specify <em>default</em> and multiple
<em>alternative</em> resources for your application:</p>
<ul>
<li>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.</li>
<li>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.</li>
</ul>
<p>For example, while your default UI
layout is saved in the {@code 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 {@code res/layout-land/}
directory. The Android system will automatically apply the appropriate resources by matching the
device's current configuration to your resource directory names.</p>
<p>Figure 1 demonstrates how a collection of default resources from an application will be applied
to two different devices when there are no alternative resources available. Figure 2 shows
the same application with a set of alternative resources that qualify for one of the device
configurations, thus, the two devices uses different resources.</p>
<p>The information above is just an introduction to how application resources work on Android.
The following documents provide a complete guide to how you can organize your application resources,
specify alternative resources, access them in your application, and more:</p>
<dl>
<dt><strong><a href="providing-resources.html">Providing Resources</a></strong></dt>
<dd>What kinds of resources you can provide in your app, where to save them, and how to create
alternative resources for specific device configurations.</dd>
<dt><strong><a href="accessing-resources.html">Accessing Resources</a></strong></dt>
<dd>How to use the resources you've provided, either by referencing them from your application
code or from other XML resources.</dd>
<dt><strong><a href="runtime-changes.html">Handling Runtime Changes</a></strong></dt>
<dd>How to manage configuration changes that occur while your Activity is running.</dd>
<dt><strong><a href="localization.html">Localization</a></strong></dt>
<dd>A bottom-up guide to localizing your application using alternative resources. While this is
just one specific use of alternative resources, it is very important in order to reach more
users.</dd>
<dt><strong><a href="available-resources.html">Resource Types</a></strong></dt>
<dd>A reference of various resource types you can provide, describing their XML elements,
attributes, and syntax. For example, this reference shows you how to create a resource for
application menus, drawables, animations, and more.</dd>
</dl>
<!--
<h2>Raw Assets</h2>
<p>An alternative to saving files in {@code res/} is to save files in the {@code
assets/} directory. This should only be necessary if you need direct access to original files and
directories by name. Files saved in the {@code assets/} directory will not be given a resource
ID, so you can't reference them through the {@code R} class or from XML resources. Instead, you can
query data in the {@code assets/} directory like an ordinary file system, search through the
directory and
read raw data using {@link android.content.res.AssetManager}. For example, this can be more useful
when dealing with textures for a game. However, if you only need to read raw data from a file
(such as a video or audio file), then you should save files into the {@code res/raw/} directory and
then read a stream of bytes using {@link android.content.res.Resources#openRawResource(int)}. This
is uncommon, but if you need direct access to original files in {@code assets/}, refer to the {@link
android.content.res.AssetManager} documentation.</p>
-->

View File

@@ -0,0 +1,224 @@
page.title=Layout Resource
parent.title=Resource Types
parent.link=available-resources.html
@jd:body
<div id="qv-wrapper">
<div id="qv">
<h2>See also</h2>
<ol>
<li><a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring Layout</a></li>
</ol>
</div>
</div>
<p>A layout resource defines the architecture for the UI in an Activity or a component of a UI.</p>
<dl class="xml">
<dt>file location:</dt>
<dd><code>res/layout/<em>filename</em>.xml</code><br/>
The filename will be used as the resource ID.</dd>
<dt>compiled resource datatype:</dt>
<dd>Resource pointer to a {@link android.view.View} (or subclass) resource.</dd>
<dt>resource reference:</dt>
<dd>
In Java: <code>R.layout.<em>filename</em></code><br/>
In XML: <code>@[<em>package</em>:]layout/<em>filename</em></code>
</dd>
<dt>syntax:</dt>
<dd>
<pre class="stx">
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;<a href="#viewgroup-element"><em>ViewGroup</em></a> xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/<em>name</em>"
android:layout_height="@+id/<em>string_name</em>"
android:layout_width="@+id/<em>string_name</em>"
[<em>other attributes</em>] &gt;
&lt;<a href="#view-element"><em>View</em></a>
android:id="@+id/<em>name</em>"
android:layout_height="@+id/<em>string_name</em>"
android:layout_width="@+id/<em>string_name</em>"
[<em>other attributes</em>] &gt;
&lt;<a href="#requestfocus-element">requestFocus</a>/&gt;
&lt;/<em>View</em>&gt;
&lt;<a href="#viewgroup-element"><em>ViewGroup</em></a> &gt;
&lt;<a href="#view-element"><em>View</em></a> /&gt;
&lt;/<em>ViewGroup</em>&gt;
&lt;/<em>ViewGroup</em>&gt;
</pre>
<p class="note"><strong>Note:</strong> The root element can be either a
{@link android.view.ViewGroup} or a {@link android.view.View}, but there must be only
one root element and it must contain the {@code xmlns:android} attribute with the {@code android}
namespace as shown.</p>
</dd>
<dt>elements:</dt>
<dd>
<dl class="tag-list">
<dt id="viewgroup-element"><code>&lt;ViewGroup&gt;</code></dt>
<dd>A container for other {@link android.view.View} elements. There are many
different kinds of {@link android.view.ViewGroup} objects and each one lets you
specify the layout of the child elements in different ways. Different kinds of
{@link android.view.ViewGroup} objects include {@link android.widget.LinearLayout},
{@link android.widget.RelativeLayout}, and {@link android.widget.FrameLayout}.
<p>You should not assume that any derivation of {@link android.view.ViewGroup}
will accept nested {@link android.view.View}s. Some {@link android.view.ViewGroup}s
are implementations of the {@link android.widget.AdapterView} class, which determines
its children only from an {@link android.widget.Adapter}.</p>
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>android:id</code></dt>
<dd><em>Resource name</em>. A unique resource name for the element, which you can
use to obtain a reference to the {@link android.view.ViewGroup} from your application.
The value takes the form: <code>"@+id/<em>name</em>"</code>. See more about the
<a href="#idvalue">value for {@code android:id}</a> below.
</dd>
<dt><code>android:layout_height</code></dt>
<dd><em>Dimension or keyword</em>. <strong>Required</strong>. The height for the group, as a
dimension value (or <a
href="more-resources.html#Dimension">dimension resource</a>) or a keyword ({@code "fill_parent"}
or {@code "wrap_content"}). See the <a href="#layoutvalues">valid values</a> below.
</dd>
<dt><code>android:layout_width</code></dt>
<dd><em>Dimension or keyword</em>. <strong>Required</strong>. The width for the group, as a
dimension value (or <a
href="more-resources.html#Dimension">dimension resource</a>) or a keyword ({@code "fill_parent"}
or {@code "wrap_content"}). See the <a href="#layoutvalues">valid values</a> below.
</dd>
</dl>
<p>More attributes are supported by the {@link android.view.ViewGroup}
base class, and many more are supported by each implementation of
{@link android.view.ViewGroup}. For a reference of all available attributes,
see the corresponding reference documentation for the {@link android.view.ViewGroup} class
(for example, the <a
href="{@docRoot}reference/android/widget/LinearLayout#lattrs">LinearLayout XML attributes</a>).</p>
</dd>
<dt id="view-element"><code>&lt;View&gt;</code></dt>
<dd>An individual UI component, generally referred to as a "widget". Different
kinds of {@link android.view.View} objects include {@link android.widget.TextView},
{@link android.widget.Button}, and {@link android.widget.CheckBox}.
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>android:id</code></dt>
<dd><em>Resource name</em>. A unique resource name for the element, which you can use to
obtain a reference to the {@link android.view.View} from your application.
The value takes the form: <code>"@+id/<em>name</em>"</code>. See more about the
<a href="#idvalue">value for {@code android:id}</a> below.
</dd>
<dt><code>android:layout_height</code></dt>
<dd><em>Dimension or keyword</em>. <strong>Required</strong>. The height for the element, as
a dimension value (or <a
href="more-resources.html#Dimension">dimension resource</a>) or a keyword ({@code "fill_parent"}
or {@code "wrap_content"}). See the <a href="#layoutvalues">valid values</a> below.
</dd>
<dt><code>android:layout_width</code></dt>
<dd><em>Dimension or keyword</em>. <strong>Required</strong>. The width for the element, as
a dimension value (or <a
href="more-resources.html#Dimension">dimension resource</a>) or a keyword ({@code "fill_parent"}
or {@code "wrap_content"}). See the <a href="#layoutvalues">valid values</a> below.
</dd>
</dl>
<p>More attributes are supported by the {@link android.view.View}
base class, and many more are supported by each implementation of
{@link android.view.View}. Read <a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring
Layout</a> for more information. For a reference of all available attributes,
see the corresponding reference documentation (for example, the <a
href="{@docRoot}reference/android/widget/TextView.html#lattrs">TextView XML attributes</a>).</p>
</dd>
<dt id="requestfocus-element"><code>&lt;requestFocus&gt;</code></dt>
<dd>Any element representing a {@link android.view.View} object can include this empty element,
which gives it's parent initial focus on the screen. You can have only one of these
elements per file.</dd>
</dl>
<h4 id="idvalue">Value for <code>android:id</code></h4>
<p>For the ID value, you should use this syntax form: <code>"@+id/<em>name</em>"</code>. The plus symbol,
{@code +}, indicates that this is a new resource ID and the aapt tool will create
a new resource number to the {@code R.java} class, if it doesn't already exist. For example:</p>
<pre>
&lt;TextView android:id="@+id/nameTextbox"/>
</pre>
<p>You can then refer to it this way in Java:</p>
<pre>
findViewById(R.id.nameTextbox);
</pre>
<h4 id="layoutvalues">Value for <code>android:layout_height</code> and
<code>android:layout_width</code>:</h4>
<p>The height and width value can be expressed using any of the
<a href="more-resources.html#Dimension">dimension
units</a> supported by Android (px, dp, sp, pt, in, mm) or with the following keywords:</p>
<table><tr><th>Value</th><th>Description</th></tr>
<tr>
<td><code>match_parent</code></td>
<td>Sets the dimension to match that of the parent element. Added in API Level 8 to
deprecate <code>fill_parent</code>.</td>
</tr>
<tr>
<td><code>fill_parent</code></td>
<td>Sets the dimension to match that of the parent element.</td>
</tr><tr>
<td><code>wrap_content</code></td>
<td>Sets the dimension only to the size required to fit the content of this element.</td>
</tr>
</table>
<h4>Custom View elements</h4>
<p>You can create your own custom {@link android.view.View} and {@link android.view.ViewGroup}
elements and apply them to your layout the same as a standard layout
element. You can also specify the attributes supported in the XML element. To learn more,
read <a href="{@docRoot}guide/topics/ui/custom-components.html">Building Custom Components</a>.
</p>
</dd> <!-- end elements and attributes -->
<dt>example:</dt>
<dd>XML file saved at <code>res/layout/main_activity.xml</code>:
<pre>
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
&lt;TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a TextView" />
&lt;Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a Button" />
&lt;/LinearLayout>
</pre>
<p>This application code will load the layout for an {@link android.app.Activity}, in the
{@link android.app.Activity#onCreate(Bundle) onCreate()} method:</dt>
<dd>
<pre>
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView.(R.layout.main_activity);
}
</pre>
</dd> <!-- end example -->
<dt>see also:</dt>
<dd>
<ul>
<li><a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring Layout</a></li>
<li>{@link android.view.View}</li>
<li>{@link android.view.ViewGroup}</li>
</ul>
</dd>
</dl>

View File

@@ -1,5 +1,5 @@
page.title=Localization
parent.title=Resources and Assets
parent.title=Application Resources
parent.link=index.html
@jd:body
@@ -25,12 +25,11 @@ defaults.</li>
<ol><li><a href="#defaults-r-important">Why Default Resources Are Important</a></li></ol>
<li><a href="#using-framework">Using Resources for Localization</a>
<ol>
<li><a href="#creating-defaults">How to Create Default Resources</a></li><li>
<a href="#creating-alternates">How to Create Alternate Resources</a></li>
<li><a href="#creating-defaults">How to Create Default Resources</a></li>
<li><a href="#creating-alternatives">How to Create Alternative Resources</a></li>
<li><a href="#resource-precedence">Which Resources Take Precedence?</a></li>
<li><a href="#referring-to-resources">Referring to Resources in Java</a></li>
</ol>
</ol>
</li>
<li><a href="#strategies">Localization Strategies</a></li>
<li><a href="#testing">Testing Localized Applications</a></li>
@@ -52,7 +51,7 @@ defaults.</li>
<ol>
<li><a
href="{@docRoot}resources/tutorials/localization/index.html">Hello, L10N Tutorial</a></li>
<li><a href="resources-i18n.html">Resources</a></li>
<li><a href="{@docRoot}guide/topics/resources/providing-resources.html">Providing Resources</a></li>
<li><a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring Layout</a></li>
<li><a href="{@docRoot}reference/android/app/Activity.html#ActivityLifecycle">Activity Lifecycle</a></li>
</ol>
@@ -80,7 +79,7 @@ functionality:</p>
<ul>
<li>You can put most or all of the <em>contents</em> of your application's
user interface into resource files, as described in this document and in <a
href="index.html">Resources</a>. </li>
href="{@docRoot}guide/topics/resources/providing-resources.html">Providing Resources</a>.</li>
<li>The <em>behavior</em> of the user interface, on the other hand, is driven
by your Java code.
For example, if users input data that needs to be formatted or sorted
@@ -107,14 +106,15 @@ resources that best match the device.</p>
<p>(This document focuses on localization and locale. For a complete description
of resource-switching and all the types of configurations that you can
specify &#8212; screen orientation, touchscreen type, and so on &#8212; see <a
href="resources-i18n.html#AlternateResources">Alternate Resources</a>.)</p>
href="{@docRoot}guide/topics/resources/providing-resources.html#AlternativeResources">Providing
Alternative Resources</a>.)</p>
<table border="0" cellspacing="0" cellpadding="0">
<tr border="0">
<td width="180" style="border: 0pt none ;"><p class="special-note">
<strong>When you write your application:</strong>
<br><br>
You create a set of default resources, plus alternates to be used in
You create a set of default resources, plus alternatives to be used in
different locales.</p></td>
<td style="border: 0pt none; padding:0">
<p style="border:0; padding:0"><img src="../../../images/resources/right-arrow.png" alt="right-arrow"
@@ -126,7 +126,7 @@ href="resources-i18n.html#AlternateResources">Alternate Resources</a>.)</p>
</tr>
</table>
<p>When you write your application, you create default and alternate resources
<p>When you write your application, you create default and alternative resources
for your application to use. To create resources, you place files within
specially named subdirectories of the project's <code>res/</code> directory.
</p>
@@ -204,18 +204,19 @@ speak. </p>
<em>default</em> string file must contain them all.
</p>
<h3 id="creating-alternates">How to Create Alternate Resources</h3>
<h3 id="creating-alternatives">How to Create Alternative Resources</h3>
<p>A large part of localizing an application is providing alternate text for
different languages. In some cases you will also provide alternate graphics,
<p>A large part of localizing an application is providing alternative text for
different languages. In some cases you will also provide alternative graphics,
sounds, layouts, and other locale-specific resources. </p>
<p>An application can specify many <code>res/<em>&lt;qualifiers&gt;</em>/</code>
directories, each with different qualifiers. To create an alternate resource for
directories, each with different qualifiers. To create an alternative resource for
a different locale, you use a qualifier that specifies a language or a
language-region combination. (The name of a resource directory must conform
to the naming scheme described in
<a href="resources-i18n.html#AlternateResources">Alternate Resources</a>,
<a href="{@docRoot}guide/topics/resources/providing-resources.html#AlternativeResources">Providing
Alternative Resources</a>,
or else it will not compile.)</p>
<p><em>Example:</em></p>
@@ -223,7 +224,7 @@ or else it will not compile.)</p>
<p>Suppose that your application's default language is English. Suppose also
that you want to localize all the text in your application to French, and most
of the text in your application (everything except the application's title) to
Japanese. In this case, you could create three alternate <code>strings.xml</code>
Japanese. In this case, you could create three alternative <code>strings.xml</code>
files, each stored in a locale-specific resource directory:</p>
<ol>
@@ -315,19 +316,21 @@ configured for Hindi. That is because in the resource-selection process, Android
will prefer an MCC match over a language match. </p>
<p>The selection process is not always as straightforward as these examples
suggest. Please read <a href="resources-i18n.html#best-match">How Android finds
the best matching directory</a> for a more nuanced description of the
suggest. Please read <a
href="{@docRoot}guide/topics/resources/creating-resources.html#BestMatch">How Android Finds
the Best-matching Resource</a> for a more nuanced description of the
process. All the qualifiers are described and listed in order of
precedence in <a href="resources-i18n.html#table2">Table 2 in the Resources
document</a>.</p>
precedence in <a
href="{@docRoot}guide/topics/resources/creating-resources.html#table2">Table 2 of Providing
Alternative Resources</a>.</p>
<h3 id="referring-to-resources">Referring to Resources in Java</h3>
<p>In your application's Java code, you refer to resources using the syntax
<code>R.<em>resource_type</em>.<em>resource_name</em></code> or
<code>android.R.<em>resource_type</em>.<em>resource_name</em></code><em>.</em>
For more about this, see <a href="resources-i18n.html#ResourcesInCode">Using
Resources in Code</a>.</p>
For more about this, see <a
href="{@docRoot}guide/topics/resources/using-resources.html">Accessing Resources</a>.</p>
<h2 id="strategies">Localization Strategies</h2>
@@ -359,7 +362,7 @@ that your application will need. </p>
<h4>Design a flexible layout</h4>
<p> If you need to rearrange your layout to fit a certain language (for example
German with its long words), you can create an alternate layout for that
German with its long words), you can create an alternative layout for that
language (for example <code>res/layout-de/main.xml</code>). However, doing this
can make your application harder to maintain. It is better to create a single
layout that is more flexible.</p>
@@ -383,10 +386,10 @@ languages.</li>
<p>You probably do not need to create a locale-specific
alternative for every resource in your application. For example, the layout
defined in the <code>res/layout/main.xml</code> file might work in any locale,
in which case there would be no need to create any alternate layout files.
in which case there would be no need to create any alternative layout files.
</p>
<p>Also, you might not need to create alternate text for every
<p>Also, you might not need to create alternative text for every
string. For example, assume the following:</p>
<ul>
@@ -395,7 +398,7 @@ English. Every string that the application uses is defined, using American
English spellings, in <code>res/values/strings.xml</code>. </li>
<li>For a few important phrases, you want to provide
British English spelling. You want these alternate strings to be used when your
British English spelling. You want these alternative strings to be used when your
application runs on a device in the United Kingdom. </li>
</ul>

View File

@@ -0,0 +1,207 @@
page.title=Menu Resource
parent.title=Resource Types
parent.link=available-resources.html
@jd:body
<div id="qv-wrapper">
<div id="qv">
<h2>See also</h2>
<ol>
<li><a href="{@docRoot}guide/topics/ui/menus.html">Creating Menus</a></li>
</ol>
</div>
</div>
<p>A menu resource defines an application menu (Options Menu, Context Menu, or Sub Menu) that
can be inflated with {@link android.view.MenuInflater}.</p>
<dl class="xml">
<dt>file location:</dt>
<dd><code>res/menu/<em>filename</em>.xml</code><br/>
The filename will be used as the resource ID.</dd>
<dt>compiled resource datatype:</dt>
<dd>Resource pointer to a {@link android.view.Menu} (or subclass) resource.</dd>
<dt>resource reference:</dt>
<dd>
In Java: <code>R.menu.<em>filename</em></code><br/>
In XML: <code>@[<em>package</em>:]menu.<em>filename</em></code>
</dd>
<dt>syntax:</dt>
<dd>
<pre>
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;<a href="#menu-element">menu</a> xmlns:android="http://schemas.android.com/apk/res/android">
&lt;<a href="#item-element">item</a> android:id="<em>resource ID</em>"
android:menuCategory=["container" | "system" | "secondary" | "alternative"]
android:orderInCategory="<em>integer</em>"
android:title="<em>string</em>"
android:titleCondensed="<em>string</em>"
android:icon="<em>drawable resource</em>"
android:alphabeticShortcut="<em>string</em>"
android:numericShortcut="<em>string</em>"
android:checkable=["true" | "false"]
android:visible=["visible" | "invisible" | "gone"]
android:enabled=["enabled" | "disabled"] /&gt;
&lt;<a href="#group-element">group</a> android:id="<em>resource ID</em>"
android:menuCategory=["container" | "system" | "secondary" | "alternative"]
android:orderInCategory="<em>integer</em>"
android:checkableBehavior=["none" | "all" | "single"]
android:visible=["visible" | "invisible" | "gone"]
android:enabled=["enabled" | "disabled"] &gt;
&lt;<a href="#item-element">item</a> /&gt;
&lt;/group&gt;
&lt;<a href="#item-element">item</a> &gt;
&lt;<a href="#menu-element">menu</a>&gt;
&lt;<a href="#item-element">item</a> /&gt;
&lt;/menu&gt;
&lt;/item&gt;
&lt;/menu&gt;
</pre>
</dd>
<dt>elements:</dt>
<dd>
<dl class="tag-list">
<dt id="menu-element"><code>&lt;menu&gt;</code></dt>
<dd><strong>Required.</strong> This must be the root node. Contains <code>&lt;item></code> and/or
<code>&lt;group></code> elements.
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>xmlns:android</code></dt>
<dd><em>String</em>. <strong>Required.</strong> Defines the XML namespace, which must be
<code>"http://schemas.android.com/apk/res/android"</code>.
</dl>
</dd>
<dt id="group-element"><code>&lt;group&gt;</code></dt>
<dd>A menu group (to create a collection of items that share traits, such as whether they are
visible, enabled, or checkable). Contains one or more <code>&lt;item&gt;</code> elements. Must be a
child of a <code>&lt;menu&gt;</code> element.
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>android:id</code></dt>
<dd><em>Resource name</em>. A unique resource name. The value takes the form:
<code>"@+id/<em>name</em>"</code>.</dd>
<dt><code>android:menuCategory</code></dt>
<dd><em>Keyword</em>. Value corresponding to {@link android.view.Menu} {@code CATEGORY_*}
constants, which define the group's priority. Valid values:
<table>
<tr><th>Value</th><th>Description</th></tr>
<tr><td><code>container</code></td><td>For groups that are part of a
container.</td></tr>
<tr><td><code>system</code></td><td>For groups that are provided by the
system.</td></tr>
<tr><td><code>secondary</code></td><td>For groups that are user-supplied secondary
(infrequently used) options.</td></tr>
<tr><td><code>alternative</code></td><td>For groups that are alternative actions
on the data that is currently displayed.</td></tr>
</table>
</dd>
<dt><code>android:orderInCategory</code></dt>
<dd><em>Integer</em>. The default order of the items within the category.</dd>
<dt><code>android:checkableBehavior</code></dt>
<dd><em>Keyword</em>. The type of checkable behavior for the group. Valid values:
<table>
<tr><th>Value</th><th>Description</th></tr>
<tr><td><code>none</code></td><td>Not checkable</td></tr>
<tr><td><code>all</code></td><td>All items can be checked (use checkboxes)</td></tr>
<tr><td><code>single</code></td><td>Only one item can be checked (use radio buttons)</td></tr>
</table>
</dd>
<dt><code>android:visible</code></dt>
<dd><em>Boolean</em>. "true" if the group is visible.</dd>
<dt><code>android:enabled</code></dt>
<dd><em>Boolean</em>. "true" if the group is enabled.</dd>
</dl>
</dd>
<dt id="item-element"><code>&lt;item&gt;</code></dt>
<dd>A menu item. May contain a <code>&lt;menu&gt;</code> element (for a Sub
Menu). Must be a child of a <code>&lt;menu&gt;</code> or <code>&lt;group&gt;</code> element.
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>android:id</code></dt>
<dd><em>Resource name</em>. A unique resource name. The value takes the form:
<code>"@+id/<em>name</em>"</code>.</dd>
<dt><code>android:menuCategory</code></dt>
<dd><em>Keyword</em>. Value corresponding to {@link android.view.Menu} {@code CATEGORY_*}
constants, which define the item's priority. Valid values:
<table>
<tr><th>Value</th><th>Description</th></tr>
<tr><td><code>container</code></td><td>For items that are part of a
container.</td></tr>
<tr><td><code>system</code></td><td>For items that are provided by the
system.</td></tr>
<tr><td><code>secondary</code></td><td>For items that are user-supplied secondary
(infrequently used) options.</td></tr>
<tr><td><code>alternative</code></td><td>For items that are alternative actions
on the data that is currently displayed.</td></tr>
</table>
</dd>
<dt><code>android:orderInCategory</code></dt>
<dd><em>Integer</em>. The order of "importance" of the item, within a group.</dd>
<dt><code>android:title</code></dt>
<dd><em>String</em>. The menu title.</dd>
<dt><code>android:titleCondensed</code></dt>
<dd><em>String</em>. A condensed title, for situations in which the normal title is
too long.</dd>
<dt><code>android:icon</code></dt>
<dd><em>Drawable resource</em>. An image to be used as the menu item icon.</dd>
<dt><code>android:alphabeticShortcut</code></dt>
<dd><em>Char</em>. A character for the alphabetic shortcut key.</dd>
<dt><code>android:numericShortcut</code></dt>
<dd><em>Integer</em>. A number for the numeric shortcut key.</dd>
<dt><code>android:checkable</code></dt>
<dd><em>Boolean</em>. "true" if the item is checkable.</dd>
<dt><code>android:checked</code></dt>
<dd><em>Boolean</em>. "true" if the item is checked by default.</dd>
<dt><code>android:visible</code></dt>
<dd><em>Boolean</em>. "true" if the item is visible by default.</dd>
<dt><code>android:enabled</code></dt>
<dd><em>Boolean</em>. "true" if the item is enabled by default.</dd>
</dl>
</dd>
</dl>
</dd>
<dt>example:</dt>
<dd>XML file saved at <code>res/menu/example_menu.xml</code>:
<pre>
&lt;menu xmlns:android="http://schemas.android.com/apk/res/android">
&lt;item android:id="@+id/example_item"
android:title="Example Item"
android:icon="@drawable/example_item_icon" />
&lt;group android:id="@+id/example_group">
&lt;item android:id="@+id/group_item1"
android:title="Group Item 1"
android:icon="@drawable/example_item1_icon" />
&lt;item android:id="@+id/group_item2"
android:title="Group Item 2"
android:icon="@drawable/example_item2_icon" />
&lt;/group>
&lt;item android:id="@+id/submenu"
android:title="Sub Menu" >
&lt;menu>
&lt;item android:id="@+id/submenu_item"
android:title="Sub Menu Item" />
&lt;/menu>
&lt;/item>
&lt;/menu>
</pre>
<p>This application code will inflate the menu from the {@link
android.app.Activity#onCreateOptionsMenu(Menu)} callback:</p>
<pre>
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.example_menu, menu);
return true;
}
</pre>
</dd> <!-- end example -->
</dl>

View File

@@ -0,0 +1,684 @@
page.title=More Resource Types
parent.title=Resource Types
parent.link=available-resources.html
@jd:body
<p>This page defines more types of resources you can externalize, including:</p>
<dl>
<dt><a href="#Bool">Bool</a></dt>
<dd>XML resource that carries a boolean value.</dd>
<dt><a href="#Color">Color</a></dt>
<dd>XML resource that carries a color value (a hexadecimal color).</dd>
<dt><a href="#Dimension">Dimension</a></dt>
<dd>XML resource that carries a dimension value (with a unit of measure).</dd>
<dt><a href="#Integer">Integer</a></dt>
<dd>XML resource that carries an integer value.</dd>
<dt><a href="#IntegerArray">Integer Array</a></dt>
<dd>XML resource that provides an array of integers.</dd>
<dt><a href="#TypedArray">Typed Array</a></dt>
<dd>XML resource that provides a {@link android.content.res.TypedArray} (which you can use
for an array of drawables).</dd>
</dl>
<h2 id="Bool">Bool</h2>
<p>A boolean value defined in XML.</p>
<p class="note"><strong>Note:</strong> A bool is a simple resource that is referenced
using the value provided in the {@code name} attribute (not the name of the XML file). As
such, you can combine bool resources with other simple resources in the one XML file,
under one {@code &lt;resources>} element.</p>
<dl class="xml">
<dt>file location:</dt>
<dd><code>res/values/<em>filename</em>.xml</code><br/>
The filename is arbitrary. The {@code &lt;bool>} element's {@code name} will be used as the resource
ID.</dd>
<dt>resource reference:</dt>
<dd>
In Java: <code>R.bool.<em>bool_name</em></code><br/>
In XML: <code>@[<em>package</em>:]bool/<em>bool_name</em></code>
</dd>
<dt>syntax:</dt>
<dd>
<pre class="stx">
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;<a href="#bool-resources-element">resources</a>&gt;
&lt;<a href="#bool-element">bool</a>
name="<em>bool_name</em>"
&gt;[true | false]&lt;/bool>
&lt;/resources>
</pre>
</dd>
<dt>elements:</dt>
<dd>
<dl class="tag-list">
<dt id="bool-resources-element"><code>&lt;resources&gt;</code></dt>
<dd><strong>Required.</strong> This must be the root node.
<p>No attributes.</p>
</dd>
<dt id="bool-element"><code>&lt;bool&gt;</code></dt>
<dd>A boolean value: {@code true} or {@code false}.
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>name</code></dt>
<dd><em>String</em>. A name for the bool value. This will be used as the resource ID.</dd>
</dl>
</dd>
</dl>
</dd> <!-- end elements and attributes -->
<dt>example:</dt>
<dd>XML file saved at <code>res/values-small/bools.xml</code>:
<pre>
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;resources&gt;
&lt;bool name="screen_small">true&lt;/bool>
&lt;bool name="adjust_view_bounds">true&lt;/bool>
&lt;/resources>
</pre>
<p>This application code retrieves the boolean:</p>
<pre>
Resources res = {@link android.content.Context#getResources()};
boolean screenIsSmall = res.{@link android.content.res.Resources#getBoolean(int) getBoolean}(R.bool.screen_small);
</pre>
<p>This layout XML uses the boolean for an attribute:</p>
<pre>
&lt;ImageView
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:src="@drawable/logo"
android:adjustViewBounds="@bool/adjust_view_bounds" />
</pre>
</dd> <!-- end example -->
</dl>
<h2 id="Color">Color</h2>
<p>A color value defined in XML.
The color is specified with an RGB value and alpha channel. A color resource can be used
any place that expects a hexadecimal color value.</p>
<p>The value always begins with a pound (#) character and then followed by the
Alpha-Red-Green-Blue information in one of the following formats:</p>
<ul>
<li>#<em>RGB</em></li>
<li>#<em>ARGB</em></li>
<li>#<em>RRGGBB</em></li>
<li>#<em>AARRGGBB</em></li>
</ul>
<p class="note"><strong>Note:</strong> A color is a simple resource that is referenced
using the value provided in the {@code name} attribute (not the name of the XML file). As
such, you can combine color resources with other simple resources in the one XML file,
under one {@code &lt;resources>} element.</p>
<dl class="xml">
<dt>file location:</dt>
<dd><code>res/values/colors.xml</code><br/>
The filename is arbitrary. The {@code &lt;color>} element's {@code name} will be used as the
resource ID.</dd>
<dt>resource reference:</dt>
<dd>
In Java: <code>R.color.<em>color_name</em></code><br/>
In XML: <code>@[<em>package</em>:]color/<em>color_name</em></code>
</dd>
<dt>syntax:</dt>
<dd>
<pre class="stx">
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;<a href="#color-resources-element">resources</a>>
&lt;<a href="#color-element">color</a>
name="<em>color_name</em>"
&gt;<em>hex_color</em>&lt;/color>
&lt;/resources>
</pre>
</dd>
<dt>elements:</dt>
<dd>
<dl class="tag-list">
<dt id="color-resources-element"><code>&lt;resources&gt;</code></dt>
<dd><strong>Required.</strong> This must be the root node.
<p>No attributes.</p>
</dd>
<dt id="color-element"><code>&lt;color&gt;</code></dt>
<dd>A color expressed in hexadecimal, as described above.
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>name</code></dt>
<dd><em>String</em>. A name for the color. This will be used as the resource ID.
</dd>
</dl>
</dd>
</dl>
</dd> <!-- end elements and attributes -->
<dt>example:</dt>
<dd>XML file saved at <code>res/values/colors.xml</code>:
<pre>
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;resources>
&lt;color name="opaque_red">#f00&lt;/color>
&lt;color name="translucent_red">#80ff0000&lt;/color>
&lt;/resources>
</pre>
<p>This application code retrieves the color resource:</p>
<pre>
Resources res = {@link android.content.Context#getResources()};
int color = res.{@link android.content.res.Resources#getColor(int) getColor}(R.color.opaque_red);
</pre>
<p>This layout XML applies the color to an attribute:</p>
<pre>
&lt;TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="@color/translucent_red"
android:text="Hello"/>
</pre>
</dd> <!-- end example -->
</dl>
<h2 id="Dimension">Dimension</h2>
<p>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:</p>
<dl>
<dt>{@code dp}</dt>
<dd>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. The
compiler accepts both "dip" and "dp", though "dp" is more consistent with "sp".</dd>
<dt>{@code sp}</dt>
<dd>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 the user's preference.</dd>
<dt>{@code pt}</dt>
<dd>Points - 1/72 of an inch based on the physical size of the screen.</dd>
<dt>{@code px}</dt>
<dd>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.</dd>
<dt>{@code mm}</dt>
<dd>Millimeters - based on the physical size of the screen.</dd>
<dt>{@code in}</dt>
<dd>Inches - based on the physical size of the screen.</dd>
</dl>
<p class="note"><strong>Note:</strong> A dimension is a simple resource that is referenced
using the value provided in the {@code name} attribute (not the name of the XML file). As
such, you can combine dimension resources with other simple resources in the one XML file,
under one {@code &lt;resources>} element.</p>
<dl class="xml">
<dt>file location:</dt>
<dd><code>res/values/<em>filename</em>.xml</code><br/>
The filename is arbitrary. The {@code &lt;dimen>} element's {@code name} will be used as the
resource ID.</dd>
<dt>resource reference:</dt>
<dd>
In Java: <code>R.dimen.<em>dimension_name</em></code><br/>
In XML: <code>@[<em>package</em>:]dimen/<em>dimension_name</em></code>
</dd>
<dt>syntax:</dt>
<dd>
<pre class="stx">
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;<a href="#dimen-resources-element">resources</a>>
&lt;<a href="#dimen-element">dimen</a>
name="<em>dimension_name</em>"
&gt;<em>dimension</em>&lt;/dimen&gt;
&lt;/resources&gt;
</pre>
</dd>
<dt>elements:</dt>
<dd>
<dl class="tag-list">
<dt id="dimen-resources-element"><code>&lt;resources&gt;</code></dt>
<dd><strong>Required.</strong> This must be the root node.
<p>No attributes.</p>
</dd>
<dt id="dimen-element"><code>&lt;dimen&gt;</code></dt>
<dd>A dimension, represented by a float, followed by a unit of measurement (dp, sp, pt, px, mm, in),
as described above.
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>name</code></dt>
<dd><em>String</em>. A name for the dimension. This will be used as the resource ID.
</dd>
</dl>
</dd>
</dl>
</dd> <!-- end elements and attributes -->
<dt>example:</dt>
<dd>XML file saved at <code>res/values/dimens.xml</code>:
<pre>
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;resources>
&lt;dimen name="textview_height">25dp&lt;/dimen>
&lt;dimen name="textview_width">150dp&lt;/dimen>
&lt;dimen name="ball_radius">30dp&lt;/dimen>
&lt;dimen name="font_size">16sp&lt;/dimen>
&lt;/resources>
</pre>
<p>This application code retrieves a dimension:</p>
<pre>
Resources res = {@link android.content.Context#getResources()};
float fontSize = res.{@link android.content.res.Resources#getDimension(int) getDimension}(R.dimen.font_size);
</pre>
<p>This layout XML applies dimensions to attributes:</p>
<pre>
&lt;TextView
android:layout_height="@dimen/textview_height"
android:layout_width="@dimen/textview_width"
android:textSize="@dimen/sixteen_sp"/>
</pre>
</dl>
</dd> <!-- end example -->
</dl>
<h2 id="Integer">Integer</h2>
<p>An integer defined in XML.</p>
<p class="note"><strong>Note:</strong> An integer is a simple resource that is referenced
using the value provided in the {@code name} attribute (not the name of the XML file). As
such, you can combine integer resources with other simple resources in the one XML file,
under one {@code &lt;resources>} element.</p>
<dl class="xml">
<dt>file location:</dt>
<dd><code>res/values/<em>filename.xml</em></code><br/>
The filename is arbitrary. The {@code &lt;integer>} element's {@code name} will be used as the
resource ID.</dd>
<dt>resource reference:</dt>
<dd>
In Java: <code>R.integer.<em>integer_name</em></code><br/>
In XML: <code>@[<em>package</em>:]integer/<em>integer_name</em></code>
</dd>
<dt>syntax:</dt>
<dd>
<pre class="stx">
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;<a href="#integer-resources-element">resources</a>>
&lt;<a href="#integer-element">integer</a>
name="<em>integer_name</em>"
&gt;<em>integer</em>&lt;/dimen&gt;
&lt;/resources&gt;
</pre>
</dd>
<dt>elements:</dt>
<dd>
<dl class="tag-list">
<dt id="integer-resources-element"><code>&lt;resources&gt;</code></dt>
<dd><strong>Required.</strong> This must be the root node.
<p>No attributes.</p>
</dd>
<dt id="integer-element"><code>&lt;integer&gt;</code></dt>
<dd>An integer.
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>name</code></dt>
<dd><em>String</em>. A name for the integer. This will be used as the resource ID.
</dd>
</dl>
</dd>
</dl>
</dd> <!-- end elements and attributes -->
<dt>example:</dt>
<dd>
<p>XML file saved at <code>res/values/integers.xml</code>:</p>
<pre>
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;resources>
&lt;integer name="max_speed">75&lt;/dimen>
&lt;integer name="min_speed">5&lt;/dimen>
&lt;/resources>
</pre>
<p>This application code retrieves an integer:</p>
<pre>
Resources res = {@link android.content.Context#getResources()};
int maxSpeed = res.{@link android.content.res.Resources#getInteger(int) getInteger}(R.integer.max_speed);
</pre>
</dd> <!-- end example -->
</dl>
<h2 id="IntegerArray">Integer Array</h2>
<p>An array of integers defined in XML.</p>
<p class="note"><strong>Note:</strong> An integer array is a simple resource that is referenced
using the value provided in the {@code name} attribute (not the name of the XML file). As
such, you can combine integer array resources with other simple resources in the one XML file,
under one {@code &lt;resources>} element.</p>
<dl class="xml">
<dt>file location:</dt>
<dd><code>res/values/<em>filename</em>.xml</code><br/>
The filename is arbitrary. The {@code &lt;integer-array>} element's {@code name} will be used as the
resource ID.</dd>
<dt>compiled resource datatype:</dt>
<dd>Resource pointer to an array of integers.</dd>
<dt>resource reference:</dt>
<dd>
In Java: <code>R.array.<em>string_array_name</em></code><br/>
In XML: <code>@[<em>package</em>:]array.<em>integer_array_name</em></code>
</dd>
<dt>syntax:</dt>
<dd>
<pre class="stx">
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;<a href="#integer-array-resources-element">resources</a>>
&lt;<a href="#integer-array-element">integer-array</a>
name="<em>integer_array_name</em>">
&lt;<a href="#integer-array-item-element">item</a>
&gt;<em>integer</em>&lt;/item&gt;
&lt;/integer-array>
&lt;/resources>
</pre>
</dd>
<dt>elements:</dt>
<dd>
<dl class="tag-list">
<dt id="integer-array-resources-element"><code>&lt;resources&gt;</code></dt>
<dd><strong>Required.</strong> This must be the root node.
<p>No attributes.</p>
</dd>
<dt id="integer-array-element"><code>&lt;string-array&gt;</code></dt>
<dd>Defines an array of integers. Contains one or more child {@code &lt;item>} elements.
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>android:name</code></dt>
<dd><em>String</em>. A name for the array. This name will be used as the resource
ID to reference the array.</dd>
</dl>
</dd>
<dt id="integer-array-item-element"><code>&lt;item&gt;</code></dt>
<dd>An integer. The value can be a referenced to another
integer resource. Must be a child of a {@code &lt;integer-array&gt;} element.
<p>No attributes.</p>
</dd>
</dl>
</dd> <!-- end elements -->
<dt>example:</dt>
<dd>XML file saved at <code>res/values/integers.xml</code>:
<pre>
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;resources>
&lt;integer-array name="bits">
&lt;item>4&lt;/item>
&lt;item>8&lt;/item>
&lt;item>16&lt;/item>
&lt;item>32&lt;/item>
&lt;/integer-array>
&lt;/resources>
</pre>
<p>This application code retrieves the integer array:</p>
<pre>
Resources res = {@link android.content.Context#getResources()};
int[] bits = res.{@link android.content.res.Resources#getIntArray(int) getIntArray}(R.array.bits);
</pre>
</dd> <!-- end example -->
</dl>
<h2 id="TypedArray">Typed Array</h2>
<p>A {@link android.content.res.TypedArray} defined in XML. You can use
this to create an array of other resources, such as drawables. Note that the array
is not required to be homogeneous, so you can create an array of mixed resource types, but
you must be aware of what and where the data types are in the array so that you can properly obtain
each item with the {@link android.content.res.TypedArray}'s {@code get...()} methods.</p>
<p class="note"><strong>Note:</strong> A typed array is a simple resource that is referenced
using the value provided in the {@code name} attribute (not the name of the XML file). As
such, you can combine typed array resources with other simple resources in the one XML file,
under one {@code &lt;resources&gt;} element.</p>
<dl class="xml">
<dt>file location:</dt>
<dd><code>res/values/<em>filename</em>.xml</code><br/>
The filename is arbitrary. The {@code &lt;array>} element's {@code name} will be used as the
resource ID.</dd>
<dt>compiled resource datatype:</dt>
<dd>Resource pointer to a {@link android.content.res.TypedArray}.</dd>
<dt>resource reference:</dt>
<dd>
In Java: <code>R.array.<em>array_name</em></code><br/>
In XML: <code>@[<em>package</em>:]array.<em>array_name</em></code>
</dd>
<dt>syntax:</dt>
<dd>
<pre class="stx">
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;<a href="#array-resources-element">resources</a>>
&lt;<a href="#array-element">array</a>
name="<em>integer_array_name</em>">
&lt;<a href="#array-item-element">item</a>&gt;<em>resource</em>&lt;/item&gt;
&lt;/array>
&lt;/resources>
</pre>
</dd>
<dt>elements:</dt>
<dd>
<dl class="tag-list">
<dt id="array-resources-element"><code>&lt;resources&gt;</code></dt>
<dd><strong>Required.</strong> This must be the root node.
<p>No attributes.</p>
</dd>
<dt id="array-element"><code>&lt;array&gt;</code></dt>
<dd>Defines an array. Contains one or more child {@code &lt;item>} elements.
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>android:name</code></dt>
<dd><em>String</em>. A name for the array. This name will be used as the resource
ID to reference the array.</dd>
</dl>
</dd>
<dt id="array-item-element"><code>&lt;item&gt;</code></dt>
<dd>A generic resource. The value can be a reference to a resource or a simple data type.
Must be a child of an {@code &lt;array&gt;} element.
<p>No attributes.</p>
</dd>
</dl>
</dd> <!-- end elements -->
<dt>example:</dt>
<dd>XML file saved at <code>res/values/arrays.xml</code>:
<pre>
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;resources>
&lt;array name="icons">
&lt;item>@drawable/home&lt;/item>
&lt;item>@drawable/settings&lt;/item>
&lt;item>@drawable/logout&lt;/item>
&lt;/array>
&lt;array name="colors">
&lt;item>#FFFF0000&lt;/item>
&lt;item>#FF00FF00&lt;/item>
&lt;item>#FF0000FF&lt;/item>
&lt;/array>
&lt;/resources>
</pre>
<p>This application code retrieves each array and then obtains the first entry in each array:</p>
<pre>
Resources res = {@link android.content.Context#getResources()};
TypedArray icons = res.{@link android.content.res.Resources#obtainTypedArray(int) obtainTypedArray}(R.array.icons);
Drawable drawable = icons.{@link android.content.res.TypedArray#getDrawable(int) getDrawable}(0);
TypedArray colors = res.{@link android.content.res.Resources#obtainTypedArray(int) obtainTypedArray}(R.array.icons);
int color = colors.{@link android.content.res.TypedArray#getColor(int,int) getColor}(0,0);
</pre>
</dd> <!-- end example -->
</dl>
<!-- TODO
<h2>Styleable Attribute</h2>
<dl class="xml">
<dt>syntax:</dt>
<dd>
<pre class="stx">
</pre>
</dd>
<dt>file location:</dt>
<dd><code>res/</code></dd>
<dt>compiled resource datatype:</dt>
<dd>Resource pointer to a {@link android.view.Menu} (or subclass) resource.</dd>
<dt>resource reference:</dt>
<dd>Java: <code>R.</code><br/>
XML:
</dd>
<dt>elements and attributes:</dt>
<dd>
<dl class="attr">
<dt><code></code></dt>
<dd></dd>
<dt><code></code></dt>
<dd>Valid attributes:
<dl>
<dt><code></code></dt>
<dd>
</dd>
<dt><code></code></dt>
<dd>
</dd>
</dl>
</dd>
</dl>
</dd>
<dt>example:</dt>
<dd>
<dl>
<dt>XML file saved at <code>res/</code>:</dt>
<dd>
<pre>
</pre>
</dd>
<dt>Java code :</dt>
<dd>
<pre>
</pre>
</dd>
</dl>
</dd>
<dt>see also:</dt>
<dd>
<ul>
<li></li>
</ul>
</dd>
</dl>
-->

View File

@@ -0,0 +1,723 @@
page.title=Providing Resources
parent.title=Application Resources
parent.link=index.html
@jd:body
<div id="qv-wrapper">
<div id="qv">
<h2>Quickview</h2>
<ul>
<li>Different types of resources belong in different sub-directories of {@code res/}</li>
<li>Alternative resources provide configuration-specific resource files</li>
</ul>
<h2>In this document</h2>
<ol>
<li><a href="#AlternativeResources">Providing Alternative Resources</a>
<ol>
<li><a href="#AliasResources">Creating alias resources</a></li>
</ol>
</li>
<li><a href="#BestMatch">How Android Finds the Best-matching Resource</a></li>
</ol>
<h2>See also</h2>
<ol>
<li><a href="accessing-resources.html">Accessing Resources</a></li>
<li><a href="available-resources.html">Resource Types</a></li>
</ol>
</div>
</div>
<p>There are several types of resource files you can
include in your application and each type belongs in a specific sub-directory of your project's
{@code res/} directory. Absolutely no files should be saved directly inside {@code res/}.</p>
<p>For example, here's the file hierarchy for a simple project:</p>
<pre class="no-pretty-print">
MyProject/
src/ <span style="color:black">
MyActivity.java </span>
res/
drawable/ <span style="color:black">
icon.png </span>
layout/ <span style="color:black">
main_layout.xml </span>
values/ <span style="color:black">
strings.xml </span>
</pre>
<p>This project includes an image resource, a layout resource, and string resource file.</p>
<p>Table 1 lists the different {@code res/} sub-directories supported
and describes the types of resource files that belong in each one.</p>
<p class="table-caption" id="table1"><strong>Table 1.</strong> Resource directories. Each directory
belongs inside the project {@code res/} directory.</p>
<table>
<tr>
<th scope="col">Directory</th>
<th scope="col">Resource Types</th>
</tr>
<tr>
<td><code>anim/</code></td>
<td>XML files that define tween animations. See <a
href="animation-resource.html">Animation Resources</a>.</td>
</tr>
<tr>
<td><code>color/</code></td>
<td>XML files that define a state list of colors. See <a href="color-list-resource.html">Color
State List Resources</a></td>
</tr>
<tr>
<td><code>drawable/</code></td>
<td><p>Bitmap files ({@code .png}, {@code .9.png}, {@code .jpg}, {@code .gif}) or XML files that
are compiled into the following Drawable resource subtypes:</p>
<ul>
<li>Bitmap files</li>
<li>Nine-Patches (re-sizable bitmaps)</li>
<li>State lists</li>
<li>Color drawables</li>
<li>Shapes</li>
<li>Animation drawables</li>
</ul>
<p>See <a href="drawable-resource.html">Drawable Resources</a>.</p>
</td>
</tr>
<tr>
<td><code>layout/</code></td>
<td>XML files that define a user interface layout.
See <a href="layout-resource.html">Layout Resource</a>.</td>
</tr>
<tr>
<td><code>menu/</code></td>
<td>XML files that define application menus, such as an Options Menu, Context Menu, or Sub
Menu. See <a href="menu-resource.html">Menu Resource</a>.</td>
</tr>
<tr>
<td><code>raw/</code></td>
<td><p>Arbitrary files to save in their raw form. Files in here are not compressed by the
system. To open these resources with a raw {@link java.io.InputStream}, call {@link
android.content.res.Resources#openRawResource(int)
Resources.openRawResource()} with the resource ID, which is {@code R.raw.<em>filename</em>}.</p>
<p>However, if you require direct access to original file names and file hierarchy, instead of
using a resource ID to access your files, you might consider saving some resources in the {@code
assets/} directory, instead of {@code res/raw/}. You can query data in the {@code assets/} directory
like an ordinary file system, search through the directory and read raw data using {@link
android.content.res.AssetManager}.</p></td>
</tr>
<tr>
<td><code>values/</code></td>
<td><p>XML files that contain simple values, such as strings, integers, and colors.</p>
<p>Unlike the other {@code res/} subdirectories, this one
can hold files that contain descriptions of more than one resource, rather than
just one resource for the file. The XML element types of an XML file in {@code values/} control
how these resources are defined in the {@code R} class. For example, a {@code &lt;string&gt;}
element will create an
{@code R.string} resource, and a {@code &lt;color&gt;} element will create an {@code R.color}
resource.</p>
<p>While the name of a file in this directory is arbitrary and not related to the name given
to a resource produced, you might want to separate different types of resources into different
files for easier maintenance. Here are some filename conventions for some of the different types
of resources you can save here:</p>
<ul>
<li>arrays.xml to define resource arrays (<a
href="more-resources.html#TypedArray">typed arrays</a>).</li>
<li>colors.xml to define <a
href="more-resources.html#Color">color values</a></li>
<li>dimens.xml to define <a
href="more-resources.html#Dimension">dimension values</a>.</li>
<li>strings.xml to define <a href="string-resource.html">string
values</a>.</li>
<li>styles.xml to define <a href="style-resource.html">styles</a>.</li>
</ul>
<p>See <a href="string-resource.html">String Resources</a>,
<a href="style-resource.html">Style Resource</a>, and
<a href="more-resources.html">More Resource Types</a>.</p>
</td>
</tr>
<tr>
<td><code>xml/</code></td>
<td>Arbitrary XML files that are compiled and can be read at runtime by calling {@link
android.content.res.Resources#getXml(int) Resources.getXML()}. Various XML configuration files
must also be saved here, such as a <a
href="{@docRoot}guide/topics/search/searchable-config.html">searchable configuration</a>.
<!-- or preferences configuration. --></td>
</tr>
</table>
<p>For more information about certain types of resources, see the <a
href="available-resources.html">Resource Types</a> documentation.</p>
<h2 id="AlternativeResources">Providing Alternative Resources</h2>
<div class="figure" style="width:441px">
<img src="{@docRoot}images/resources/resource_devices_diagram2.png" height="137" alt="" />
<p class="img-caption">
<strong>Figure 1.</strong> Two device configurations, one using alternative resources.</p>
</div>
<p>Almost every application should provide alternative resources to support specific device
configurations. For instance, you should include different drawable resources for different
screen densities and different string resources for different languages. At runtime, Android
will automatically detect the current device configuration and then load the appropriate
resources.</p>
<p>For each set of resources for which you want to provide configuration-specific alternatives:</p>
<ol>
<li>Create a new directory in {@code res/} named in the form {@code
<em>&lt;resources_name&gt;</em>-<em>&lt;config_qualifier&gt;</em>}.
<ul>
<li><em>{@code &lt;resources_name&gt;}</em> is the directory name of the corresponding default
resources.</li>
<li><em>{@code &lt;config_qualifier&gt;}</em> is a name that specifies a configuration
for which these resources are to be used.</li>
</ul>
<p>You can append more than one <em>{@code &lt;config_qualifier&gt;}</em>. Separate each
one with a dash.</p>
</li>
<li>Save your alternative resources in this directory, named exactly the same as the default
resource files.</li>
</ol>
<p>For example, here are some default and alternative resources:</p>
<pre class="no-pretty-print">
res/
drawable/ <span style="color:black">
icon.png
background.png </span>
drawable-hdpi/ <span style="color:black">
icon.png
background.png </span>
</pre>
<p>The {@code hdpi} qualifier indicates that the resources are for devices with a high-density
screen. While the images in each directory are different, the filenames are
identical. This way, the resource ID that you use to reference the {@code icon.png} image is
always the same. When you request the {@code icon} drawable, Android will select the
version of that drawable that best matches the current device configuration.</p>
<p>Android supports several configuration qualifiers and you can
add multiple qualifiers to one directory name in order to further specify the configuration, by
separating the qualifiers with dashes. Table 2 lists the valid configuration qualifiers, in order
of precedence&mdash;they must be specified in the directory name in the order that they are listed
in the table.</p>
<p class="table-caption" id="table2"><strong>Table 2.</strong> Alternative resource qualifier
names.</p>
<table border="1">
<tr>
<th>Qualifier</th>
<th>Values</th>
<th>Description</th>
</tr>
<tr>
<td>MCC and MNC</td>
<td>Examples:<br/>
<code>mcc310</code><br/>
<code><nobr>mcc310-mnc004</nobr></code><br/>
<code>mcc208-mnc00</code><br/>
etc.
</td>
<td>
<p>Specifies resources based on the mobile country code (MCC), optionally followed by mobile
network code (MNC)
from the SIM in the device. For example, <code>mcc310</code> is U.S. on any carrier,
<code>mcc310-mnc004</code> is U.S. on Verizon, and <code>mcc208-mnc00</code> is France on
Orange.</p>
<p>If the device uses a radio connection (GSM phone), the MCC will come
from the SIM, and the MNC will come from the network to which the
device is attached.</p>
<p>You might sometimes use the MCC alone, for example to include country-specific legal
resources in your application, but if you only need to specify based on language, then use the
language and region qualifier below. If you decide to use the MCC and MNC qualifier, you
should do so with great care and completely test that it works as expected.</p></td>
</tr>
<tr>
<td>Language and region</td>
<td>Examples:<br/>
<code>en</code><br/>
<code>fr</code><br/>
<code>en-rUS</code><br/>
<code>fr-rFR</code><br/>
<code>fr-rCA</code><br/>
etc.
</td>
<td><p>This is defined by a two-letter <a
href="http://www.loc.gov/standards/iso639-2/php/code_list.php">ISO
639-1</a> language code, optionally followed by a two letter
<a
href="http://www.iso.org/iso/en/prods-services/iso3166ma/02iso-3166-code-lists/list-en1.html">ISO
3166-1-alpha-2</a> region code (preceded by lowercase &quot;r&quot;).
</p><p>
The codes are <em>not</em> case-sensitive; the {@code r} prefix is used to
distinguish the region portion.
You cannot specify a region alone.</p>
<p>This can change during the life
of your application if the user changes their language in the system settings. See <a
href="runtime-changes.html">Handling Runtime Changes</a> for information about
how this can affect your application during runtime.</p>
<p>See <a href="localization.html">Localization</a> for a complete guide to localizing
your application for other langauges.</p>
</td>
</tr>
<tr>
<td>Screen size</td>
<td>
<code>small</code><br/>
<code>normal</code><br/>
<code>large</code>
</td>
<td>
<ul>
<li> <b>Small screens</b> are based on the space available on a
QVGA low density screen. Considering a portrait HVGA display, this has
the same available width but less height -- it is 3:4 vs. HVGA's
2:3 aspect ratio. Examples are QVGA low density and VGA high
density.</li>
<li> <b>Normal screens</b> are based on the traditional Android HVGA
medium density screen. A screen is considered to be normal if it is
at least this size (independent of density) and not larger. Examples
of such screens a WQVGA low density, HVGA medium density, WVGA
high density.</li>
<li> <b>Large screens</b> are based on the space available on a
VGA medium density screen. Such a screen has significantly more
available space in both width and height than an HVGA display.
Examples are VGA and WVGA medium density screens.</li>
</ul>
<p>See <a href="{@docRoot}guide/practices/screens_support.html">Supporting Multiple
Screens</a> for more information.</p>
</td>
</tr>
<tr>
<td>Wider/taller screens</td>
<td>
<code>long</code><br/>
<code>notlong</code>
</td>
<td>
<p>This is based purely on the aspect ratio of the screen (a "long" screen is wider):
<ul>
<li><strong>Long</strong>: WQVGA, WVGA, FWVGA</li>
<li><strong>Not long</strong>: QVGA, HVGA, and VGA</li>
</ul>
<p>This is not related to the screen orientation.</p>
</td>
</tr>
<tr>
<td>Screen orientation</td>
<td>
<code>port</code><br/>
<code>land</code> <!-- <br/>
<code>square</code> -->
</td>
<td>
<p>Portrait orientation ({@code port}) is vertical and landscape orientation
({@code land}) is horizontal. <!-- Square mode is currently not used. --> </p>
<p>This can change during the life of your application if the user rotates the
screen. See <a href="runtime-changes.html">Handling Runtime Changes</a> for information about
how this affects your application during runtime.</p>
</td>
</tr>
<tr>
<td>Dock mode</td>
<td>
<code>car</code><br/>
<code>desk</code>
</td>
<td>
<p>These configurations can be initiated when the device is placed in a dock.</p>
<p><em>Added in API Level 8.</em></p>
<p>This can change during the life of your application if the user places the device in a
dock. See <a href="runtime-changes.html">Handling Runtime Changes</a> for
information about how this affects your application during runtime. Also see {@link
android.app.UiModeManager}.</p>
</td>
</tr>
<tr>
<td>Night mode</td>
<td>
<code>night</code><br/>
<code>notnight</code>
</td>
<td>
<p>
These configurations can be initiated by the device light sensor (if available).</p>
<p><em>Added in API Level 8.</em></p>
<p>This can change during the life of your application if the device determines that the
user environment is a "night" (dark) setting. See <a href="runtime-changes.html">Handling Runtime
Changes</a> for information about how this affects your application during runtime. You can
also explicitly set this mode using {@link android.app.UiModeManager}.</p>
</td>
</tr>
<tr>
<td>Screen pixel density (dpi)</td>
<td>
<code>ldpi</code><br/>
<code>mdpi</code><br/>
<code>hdpi</code><br/>
<code>nodpi</code>
</td>
<td>
<p>The medium
density of traditional HVGA screens (mdpi) is defined to be approximately
160dpi; low density (ldpi) is 120, and high density (hdpi) is 240. There
is thus a 4:3 scaling factor between each density, so a 9x9 bitmap
in ldpi would be 12x12 in mdpi and 16x16 in hdpi. The special
<code>nodpi</code> density can be used with bitmap resources to prevent
them from being scaled at load time to match the device density.
</p><p>
When Android selects which resource files to use,
it handles screen density differently than the other qualifiers.
In step 1 of <a href="#BestMatch">How Android finds the best
matching directory</a> (below), screen density is always considered to
be a match. In step 4, if the qualifier being considered is screen
density, Android will select the best final match at that point,
without any need to move on to step 5.
</p>
<p>See <a href="{@docRoot}guide/practices/screens_support.html">Supporting Multiple
Screens</a> for more information.</p>
</td>
</tr>
<tr>
<td>Touchscreen type</td>
<td>
<code>notouch</code><br/>
<code>stylus</code><br/>
<code>finger</code>
</td>
<td><p>If the device has a resistive touch screen that's suited for use with a stylus,
then it may use the {@code stylus} resources.</p>
</td>
</tr>
<tr>
<td>Keyboard availability</td>
<td>
<code>keysexposed</code><br/>
<code>keyshidden</code><br/>
<code>keyssoft</code>
</td>
<td>
<p>If your application has specific resources that should only be used with a soft keyboard,
use the <code>keyssoft</code> value. If you do not provide <code>keyssoft</code> resources, but do
provide <code>keysexposed</code> and <code>keyshidden</code>, and the device shows a soft keyboard,
the system will use <code>keysexposed</code> resources.</p>
<p>This can change during the life of your application if the user opens a keyboard. See <a
href="runtime-changes.html">Handling Runtime Changes</a> for information about how this affects your
application during runtime.</p>
</td>
</tr>
<tr>
<td>Primary text input method</td>
<td>
<code>nokeys</code><br/>
<code>qwerty</code><br/>
<code>12key</code>
</td>
<td><p>If the device has no hardware keys for text input, then it may use the {@code
nokeys} resources. Even if the device has a QWERTY keyboard but it is currently hidden, it may use
the {@code qwerty} resources.</td>
</tr>
<tr>
<td>Navigation key availability</td>
<td>
<code>navexposed</code><br/>
<code>navhidden</code>
</td>
<td>
<p>
If the device's navigation keys are currently available to
the user, it may use the {@code navexposed} resources; if they are not
available (such as behind a closed lid), it may use the {@code navhidden} resources.</p>
<p>This can change during the life of your application if the user reveals the navigation
keys. See <a href="runtime-changes.html">Handling Runtime Changes</a> for
information about how this affects your application during runtime.</p>
</td>
</tr>
<tr>
<td>Primary non-touch navigation method</td>
<td>
<code>nonav</code><br/>
<code>dpad</code><br/>
<code>trackball</code><br/>
<code>wheel</code>
</td>
<td><p>If the device has no navigation facility other than using the touchscreen, then it
may use the {@code nonav} resources.</p>
</td>
</tr>
<!-- DEPRECATED
<tr>
<td>Screen dimensions</td>
<td>Examples:<br/>
<code>320x240</code><br/>
<code>640x480</code><br/>
etc.
</td>
<td>
<p>The larger dimension must be specified first. <strong>This configuration is deprecated
and should not be used</strong>. Instead use "screen size," "wider/taller screens," and "screen
orientation" described above.</p>
</td>
</tr>
-->
<tr>
<td>API Level</td>
<td>Examples:<br/>
<code>v4</code><br/>
<code>v5</code><br/>
<code>v6</code><br/>
<code>v7</code><br/>
etc.</td>
<td>
<p>The API Level supported by the device, for example <code>v1</code> for API Level 1
(Android 1.0) or <code>v5</code> for API Level 5 (Android 2.0). See the <a
href="{@docRoot}guide/appendix/api-levels.html">Android API Levels</a> document for more information
about these values.</p>
</td>
</tr>
</table>
<p>Here are some important rules about using resource qualifier names:</p>
<ul>
<li>You can specify multiple qualifiers for a single set of resources, separated by dashes. For
example, <code>drawable-en-rUS-land</code> applies to US-English devices in landscape
orientation.</li>
<li>The qualifiers must be in the order listed in <a href="#table2">Table 2</a> above. For
example:
<ul>
<li>Wrong: <code>drawable-hdpi-port/</code></li>
<li>Correct: <code>drawable-port-hdpi/</code></li>
</ul>
</li>
<li>Qualified directories cannot be nested. For example, you cannot have
<code>res/drawable/drawable-en/</code>.</li>
<li>Values are case-insensitive. The resource compiler converts directory names
to lower case before processing to avoid problems on case-insensitive
file systems. Any capitalization in the names is only to benefit readability.</li>
<li>Only one value for each qualifier type is supported. For example, if you want to use
the same drawable files for Spain and France, you <em>cannot</em> have a directory named
<code>drawable-rES-rFR/</code>. Instead you need two resource directories, such as
<code>drawable-rES/</code> and <code>drawable-rFR/</code>, which contain the appropriate files.
However, you are not required to actually duplicate the same files in both locations (which
could multiply the size of your package if the files are large). Instead, you can create a
reference to one instance of the resources. See <a href="#AliasResources">Creating
alias resources</a>, below.</li>
</ul>
<h3 id="AliasResources">Creating alias resources</h3>
<p>When you have a resource that you'd like to use for more than one device
configuration (but not for all configurations), you <em>don't</em> have to put the same resource in
each of the alternative resource directories. Instead, you can (in some cases) create an alternative
resource that acts as an alias for a resource saved in your default resource directory.</p>
<p>For example, imagine you have an image, {@code icon.png}, and you have different versions of it
for different locales, but two locales, English-Canadian and French-Canadian, need to
use the same version. You might assume that you need to copy the Canadian version of the
icon into the alternative resource directory for both English-Canadian and French-Canadian, but it's
not true. What you can do instead is save the Canadian version as {@code icon_ca.png} (any name
other than {@code icon.png}) and put
it in the default {@code res/drawable/} directory. Then create an {@code icon.xml} file in {@code
res/drawable-en-rCA/} and {@code res/drawable-fr-rCA/} that refers to the {@code icon_ca.png}
resource using the {@code &lt;bitmap&gt;} element. This allows you to store just one version of the
PNG file and two small XML files that point to it. (An example XML file is shown below.)</p>
<p class="note"><strong>Note:</strong> Not all resources offer a mechanism by which you can
create an alias to another resource. In particular, animation, menu, raw, and other unspecified
resources in the {@code xml/} directory don't provide this kind of feature.</p>
<h4>Drawable</h4>
<p>To create an alias to an existing drawable, use the {@code &lt;bitmap&gt;} element.
For example:</p>
<pre>
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/icon_ca" />
</pre>
<p>If you save this file as {@code icon.xml}, it will be compiled into a resource that you
can reference as {@code R.drawable.icon}, but is actually an alias for the {@code
R.drawable.icon_ca} resource.</p>
<h4>Layout</h4>
<p>To create an alias to an existing layout, use the {@code &lt;include&gt;}
element, wrapped in a {@code &lt;merge&gt;}. For example:</p>
<pre>
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;merge>
&lt;include layout="@layout/main_ltr"/>
&lt;/merge>
</pre>
<p>If you save this file as {@code main.xml}, it will be compiled into a resource you can reference
as {@code R.layout.main}, but is actually an alias for the {@code R.layout.main_ltr}
resource.</p>
<h4>Strings and other simple values</h4>
<p>To create an alias to an existing string, simply use the resource ID of the desired
string as the value for the new string. For example:</p>
<pre>
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;resources>
&lt;string name="hello">Hello&lt;/string>
&lt;string name="hi">@string/hello&lt;/string>
&lt;/resources>
</pre>
<p>The {@code R.string.hi} resource is now an alias for the {@code R.string.hello}.</p>
<p> <a href="{@docRoot}guide/topics/resources/more-resources.html">Other simple values</a> work the
same way. For example, a color:</p>
<pre>
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;resources>
&lt;color name="yellow">#f00&lt;/color>
&lt;color name="highlight">@color/red&lt;/color>
&lt;/resources>
</pre>
<h2 id="BestMatch">How Android Finds the Best-matching Resource</h2>
<p>Once you have saved alternative resources for your application, Android will pick which of the
various underlying resource files should be used at runtime for each resource
requested, depending on the current device configuration. To demonstrate how Android will select the
resource to use, assume the following drawables are available:</p>
<pre class="no-pretty-print">
res/drawable/
res/drawable-en/
res/drawable-fr-rCA/
res/drawable-en-port/
res/drawable-en-notouch-12key/
res/drawable-port-ldpi/
res/drawable-port-notouch-12key
</pre>
<p>And assume the following is the device configuration:</p>
<p style="margin-left:2em;">
Locale = <code>en-GB</code> <br/>
Screen orientation = <code>port</code> <br/>
Screen pixel density = <code>hdpi</code> <br/>
Touchscreen type = <code>notouch</code> <br/>
Primary text input method = <code>12key</code>
</p>
<p>Here is how Android makes the drawable selection and how a drawable will be selected from the
configuration above: </p>
<ol>
<li>Eliminate resource files that contradict the device configuration.
<p>The <code>drawable-fr-rCA/</code> directory will be eliminated, because it
contradicts the locale of the device.</p>
<pre class="no-pretty-print">
drawable/
drawable-en/
<strike>drawable-fr-rCA/</strike>
drawable-en-port/
drawable-en-notouch-12key/
drawable-port-ldpi/
drawable-port-notouch-12key
</pre>
<p class="note"><strong>Exception: </strong>Screen pixel density is the one qualifier that is not
used to eliminate files. Even though the screen density of the device is mdpi,
<code>drawable-port-ldpi/</code> is not eliminated because every screen density is
considered to be a match at this point.</p></li>
<li>From <a href="#table2">Table 2</a>, pick the (next) highest-precedence qualifier in
the list. (Start with MCC, then move down through the list.) </li>
<li>Do any of the available resource directories include this qualifier? </li>
<ul>
<li>If No, return to step 2 and look at the next qualifier. In the example,
the answer is &quot;no&quot; until the language qualifier is reached.</li>
<li>If Yes, move on to step 4.</li>
</ul>
</li>
<li>Eliminate resource directories that do not include this qualifier. In the example, the system
eliminates all the directories that do not include a language qualifier:</li>
<pre class="no-pretty-print">
<strike>drawable/</strike>
drawable-en/
drawable-en-port/
drawable-en-notouch-12key/
<strike>drawable-port-ldpi/</strike>
<strike>drawable-port-notouch-12key</strike>
</pre>
<p class="note"><strong>Exception:</strong> If the qualifier in question is screen pixel density,
Android will
select the option that most closely matches the device, and the selection process will be complete.
In general, Android will prefer scaling down a larger original image to scaling up a smaller
original image.</p>
</li>
<li>Go back and repeat steps 2, 3, and 4 until only one choice remains. In the example, screen
orientation is the next qualifier for which there are any matches.
So, resources that do not specify a screen orientation are eliminated:
<pre class="no-pretty-print">
<strike>drawable-en/</strike>
drawable-en-port/
<strike>drawable-en-notouch-12key/</strike>
</pre>
<p>Only one choice remains, so the drawable will be taken from the {@code drawable-en-port}
directory.</p>
</li>
</ol>
<p>Though this procedure is executed for each resource requested, the system will further optimize
some aspects. One such optimization is that once the device configuration is known, it might
completely eliminate alternative resources that can never match. For example, if the configuration
language is English ("en"), then any resource directory that has a language qualifier set to
something other than English will never be included in the pool of resources checked (though a
resource directory <em>without</em> the language qualifier is still included).</p>
<p class="note"><strong>Note:</strong> The <em>precedence</em> of the qualifier (in <a
href="#table2">Table 2</a>) is more important
than the number of qualifiers that exactly match the device. For example, in step 4 above, the last
choice on the list includes three qualifiers that exactly match the device (orientation, touchscreen
type, and input method), while <code>drawable-en</code> has only one parameter that matches
(language). However, language has a higher precedence than these other qualifiers, so
<code>drawable-port-notouch-12key</code>
is out.</p>
<p>The following flowchart summarizes how Android selects the resource directory to use.</p>
<p><img src="{@docRoot}images/resources/res-selection-flowchart.png" alt=""
height="471" /></p>

View File

@@ -1,808 +1,8 @@
page.title=Resources and Internationalization
parent.title=Resources and Assets
parent.link=index.html
page.title=Application Resources
@jd:body
<div id="qv-wrapper">
<div id="qv">
<script type="text/javascript">
window.location = toRoot + "guide/topics/resources/index.html";
</script>
<h2>Key classes</h2>
<ol>
<li>{@link android.content.res.Resources}</li>
</ol>
<h2>In this document</h2>
<ol>
<li><a href="#intro">Introduction</a></li>
<li><a href="#CreatingResources">Creating Resources</a></li>
<li><a href="#UsingResources">Using Resources</a>
<ol>
<li><a href="#ResourcesInCode">Using Resources in Code</a></li>
<li><a href="#ReferencesToResources">References to Resources</a></li>
<li><a href="#ReferencesToThemeAttributes">References to Theme Attributes</a></li>
<li><a href="#UsingSystemResources">Using System Resources</a></li>
</ol>
</li>
<li><a href="#AlternateResources">Alternate Resources</a></li>
<li><a href="#ResourcesTerminology">Terminology</a></li>
<li><a href="#i18n">Internationalization (I18N)</a></li>
</ol>
</div>
</div>
<p>Resources are external files (that is, non-code files) that are used by
your code and compiled into your application at build time. Android
supports a number of different kinds of resource files, including XML,
PNG, and JPEG files. The XML files have very different formats depending
on what they describe. This document describes what kinds of files are
supported, and the syntax or format of each.</p>
<p>Resources are externalized from source code, and XML files are compiled into
a binary, fast loading format for efficiency reasons. Strings, likewise, are compressed
into a more efficient storage form. It is for these reasons that we have these
different resource types in the Android platform.</p>
<p>This is a fairly technically dense document, and together with the
<a href="available-resources.html">Available Resources</a>
document, they cover a lot of information about resources. It is not necessary
to know this document by heart to use Android, but rather to know that the
information is here when you need it.</p>
<a name="intro"></a>
<h2>Introduction</h2>
<p>This topic includes a terminology list associated with resources, and a series
of examples of using resources in code. For a complete guide to the supported
Android resource types, see
<a href="available-resources.html">Available Resources</a>.
</p>
<p>The Android resource system keeps track of all non-code
assets associated with an application. You use the
{@link android.content.res.Resources Resources} class to access your
application's resources; the Resources instance associated with your
application can generally be found through
{@link android.content.Context#getResources Context.getResources()}.</p>
<p>An application's resources are compiled into the application
binary at build time for you by the build system. To use a resource,
you must install it correctly in the source tree and build your
application. As part of the build process, symbols for each
of the resources are generated that you can use in your source
code -- this allows the compiler to verify that your application code matches
up with the resources you defined.</p>
<p>The rest of this section is organized as a tutorial on how to
use resources in an application.</p>
<a name="CreatingResources" id="CreatingResources"></a>
<h2>Creating Resources</h2>
<p>Android supports string, bitmap, and many other types of resource. The syntax and format
of each, and where they're stored, depends upon the type of object. In
general, though, you create resources from three types of files: XML files
(everything but bitmaps and raw), bitmap files(for images) and Raw files (anything
else, for example sound files, etc.). In fact, there are two different types of
XML file as well, those that get compiled as-is into the package, and those that
are used to generate resources by aapt. Here is a list of each
resource type, the format of the file, a description of the file, and details
of any XML files. </p>
<p>You will create and store your resource files under the appropriate
subdirectory under the <code>res/</code> directory in your project. Android
has a resource compiler (aapt) that compiles resources according to which
subfolder they are in, and the format of the file. Table 1 shows a list of the file
types for each resource. See the
<a href="available-resources.html">Available Resources</a> for
descriptions of each type of object, the syntax, and the format or syntax of
the containing file.</p>
<p class="caption">Table 1</p>
<table width="100%" border="1">
<tr>
<th scope="col">Directory</th>
<th scope="col">Resource Types </th>
</tr>
<tr>
<td><code>res/anim/</code></td>
<td>XML files that are compiled into
<a href="available-resources.html#animationdrawable">frame by
frame animation</a> or
<a href="available-resources.html#tweenedanimation">tweened
animation</a> objects </td>
</tr>
<tr>
<td><code>res/drawable/</code></td>
<td><p>.png, .9.png, .jpg files that are compiled into the following
Drawable resource subtypes:</p>
<ul class="nolist">
<li><a href="available-resources.html#imagefileresources">bitmap files</a></li>
<li><a href="available-resources.html#ninepatch">9-patches (resizable bitmaps)</a></li>
</ul>
<p>To get a resource of this type, use <code>mContext.getResources().getDrawable(R.drawable.<em>imageId</em>)</code></p>
<p class="note"><strong>Note:</strong> Image resources placed in here may
be automatically optimized with lossless image compression by the
<a href="{@docRoot}guide/developing/tools/aapt.html">aapt</a> tool. For example, a true-color PNG
that does not require more than 256 colors may be converted to an 8-bit PNG with a color palette.
This will result in an image of equal quality but which requires less memory. So be aware that the
image binaries placed in this directory can change during the build. If you plan on reading
an image as a bit stream in order to convert it to a bitmap, put your images in the
<code>res/raw/</code> folder instead, where they will not be optimized.</p>
</td>
</tr>
<tr>
<td><code>res/layout/</code></td>
<td>XML files that are compiled into screen layouts (or part of a screen).
See <a href="{@docRoot}guide/topics/ui/declaring-layout.html">Declaring Layout</a>.</td>
</tr>
<tr>
<td><code>res/values/</code></td>
<td><p>XML files that can be compiled into many kinds of resource.</p>
<p class="note"><strong>Note:</strong> Unlike the other res/ folders, this one
can hold any number of files that hold descriptions of resources to create
rather than the resources themselves. The XML element types control
where these resources are placed under the R class.</p>
<p>While the files can be named anything, these are
the typical files in this folder (the convention is to name
the file after the type of elements defined within):</p>
<ul>
<li><strong>arrays.xml</strong> to define arrays </li>
<!-- TODO: add section on arrays -->
<li><strong>colors.xml</strong> to define <a href="available-resources.html#colordrawableresources">color
drawables</a> and <a href="#colorvals">color string values</a>.
Use <code>Resources.getDrawable()</code> and
<code>Resources.getColor(), respectively,</code>
to get these resources.</li>
<li><strong>dimens.xml</strong> to define <a href="available-resources.html#dimension">dimension value</a>. Use <code>Resources.getDimension()</code> to get
these resources.</li>
<li><strong>strings.xml</strong> to define <a href="available-resources.html#stringresources">string</a> values (use either
<code>Resources.getString</code> or preferably <code>Resources.getText()</code>
to get
these resources. <code>getText()</code> will retain any rich text styling
which is usually desirable for UI strings.</li>
<li><strong>styles.xml</strong> to define <a href="available-resources.html#stylesandthemes">style</a> objects.</li>
</ul></td>
</tr>
<tr>
<td><code>res/xml/</code></td>
<td>Arbitrary XML files that are compiled and can be read at run time by
calling {@link android.content.res.Resources#getXml(int) Resources.getXML()}.</td>
</tr>
<tr>
<td><code>res/raw/</code></td>
<td>Arbitrary files to copy directly to the device. They are added uncompiled
to the compressed file that your application build produces. To use these
resources in your application, call {@link android.content.res.Resources#openRawResource(int)
Resources.openRawResource()} with the resource ID, which is R.raw.<em>somefilename</em>.</td>
</tr>
</table>
<p>Resources are compiled into the final APK file. Android creates a wrapper class,
called R, that you can use to refer to these resources in your code. R contains subclasses
named according to the path and file name of the source file</p>
<a name="colorvals" id="colorvals"></a>
<h3>Global Resource Notes</h3>
<ul>
<li>Several resources allow you to define colors. Android accepts color values
written in various web-style formats -- a hexadecimal constant in any of the
following forms: #RGB, #ARGB, #RRGGBB, #AARRGGBB. </li>
<li>All color values support setting an alpha channel value, where the first
two hexadecimal numbers specify the transparency. Zero in the alpha channel
means transparent. The default value is opaque. </li>
</ul>
<a name="UsingResources" id="UsingResources"></a>
<h2>Using Resources </h2>
<p>This section describes how to use the resources you've created. It includes the
following topics:</p>
<ul>
<li><a href="#ResourcesInCode">Using resources in code</a>&nbsp;- How to call
resources in your code to instantiate them. </li>
<li><a href="#ReferencesToResources">Referring to resources from other resources</a> &nbsp;-
You can reference resources from other resources. This lets you reuse common
resource values inside resources. </li>
<li><a href="#AlternateResources">Supporting Alternate Resources for Alternate
Configurations</a> - You can specify different resources
to load, depending on the language or display configuration of the host
hardware. </li>
</ul>
<p>At compile time, Android generates a class named R that contains resource identifiers
to all the resources in your program. This class contains several subclasses,
one for each type of resource supported by Android, and for which you provided
a resource file. Each class contains one or more identifiers for the compiled resources,
that you use in your code to load the resource. Here is a small resource file
that contains string, layout (screens or parts of screens), and image resources.</p>
<p class="note"><strong>Note:</strong> the R class is an auto-generated file and is not
designed to be edited by hand. It will be automatically re-created as needed when
the resources are updated.</p>
<pre class="prettyprint">package com.android.samples;
public final class R {
public static final class string {
public static final int greeting=0x0204000e;
public static final int start_button_text=0x02040001;
public static final int submit_button_text=0x02040008;
public static final int main_screen_title=0x0204000a;
};
public static final class layout {
public static final int start_screen=0x02070000;
public static final int new_user_pane=0x02070001;
public static final int select_user_list=0x02070002;
};
public static final class drawable {
public static final int company_logo=0x02020005;
public static final int smiling_cat=0x02020006;
public static final int yellow_fade_background=0x02020007;
public static final int stretch_button_1=0x02020008;
};
};
</pre>
<a name="ResourcesInCode" id="ResourcesInCode"></a>
<h3>Using Resources in Code </h3>
<p>Using resources in code is just a matter of knowing the full resource ID
and what type of object your resource has been compiled into. Here is the
syntax for referring to a resource:</p>
<p><code>R.<em>resource_type</em>.<em>resource_name</em></code></p>
<p>or</p>
<p><code>android.R.<em>resource_type</em>.<em>resource_name</em></code></p>
<p>Where <code>resource_type</code> is the R subclass that holds a specific type
of resource. <code>resource_name</code> is the <em>name</em> attribute for resources
defined in XML files, or the file name (without the extension) for resources
defined by other file types. Each type of resource will be added to a specific
R subclass, depending on the type of resource it is; to learn which R subclass
hosts your compiled resource type, consult the
<a href="available-resources.html">Available Resources</a> document. Resources compiled by your own application can
be referred to without a package name (simply as
<code>R.<em>resource_type</em>.<em>resource_name</em></code>). Android contains
a number of standard resources, such as screen styles and button backgrounds. To
refer to these in code, you must qualify them with <code>android</code>, as in
<code>android.R.drawable.button_background</code>.</p>
<p>Here are some good and bad examples of using compiled resources in code:</p>
<pre class="prettyprint">// Load a background for the current screen from a drawable resource.
this.getWindow().setBackgroundDrawableResource(R.drawable.my_background_image);
// WRONG Sending a string resource reference into a
// method that expects a string.
this.getWindow().setTitle(R.string.main_title);
// RIGHT Need to get the title from the Resources wrapper.
this.getWindow().setTitle(Resources.getText(R.string.main_title));
// Load a custom layout for the current screen.
setContentView(R.layout.main_screen);
// Set a slide in animation for a ViewFlipper object.
mFlipper.setInAnimation(AnimationUtils.loadAnimation(this,
R.anim.hyperspace_in));
// Set the text on a TextView object.
TextView msgTextView = (TextView)findViewByID(R.id.msg);
msgTextView.setText(R.string.hello_message); </pre>
<a name="ReferencesToResources" id="ReferencesToResources"></a>
<h3>References to Resources</h3>
<p>A value supplied in an attribute (or resource) can also be a reference to
a resource. This is often used in layout files to supply strings (so they
can be localized) and images (which exist in another file), though a reference
can be any resource type including colors and integers.</p>
<p>For example, if we have
<a href="available-resources.html#colordrawableresources">color
resources</a>, we can write a layout file that sets the text color size to be
the value contained in one of those resources:</p>
<pre>
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;EditText id=&quot;text&quot;
xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
android:layout_width=&quot;fill_parent&quot; android:layout_height=&quot;fill_parent&quot;
<strong>android:textColor=&quot;&#64;color/opaque_red&quot;</strong>
android:text=&quot;Hello, World!&quot; /&gt;
</pre>
<p>Note here the use of the '@' prefix to introduce a resource reference -- the
text following that is the name of a resource in the form
of <code>@[package:]type/name</code>. In this case we didn't need to specify
the package because we are referencing a resource in our own package. To
reference a system resource, you would need to write:</p>
<pre>
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;EditText id=&quot;text&quot;
xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
android:layout_width=&quot;fill_parent&quot; android:layout_height=&quot;fill_parent&quot;
android:textColor=&quot;&#64;<strong>android:</strong>color/opaque_red&quot;
android:text=&quot;Hello, World!&quot; /&gt;
</pre>
<p>As another example, you should always use resource references when supplying
strings in a layout file so that they can be localized:</p>
<pre>
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;EditText id=&quot;text&quot;
xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
android:layout_width=&quot;fill_parent&quot; android:layout_height=&quot;fill_parent&quot;
android:textColor=&quot;&#64;android:color/opaque_red&quot;
android:text=&quot;&#64;string/hello_world&quot; /&gt;
</pre>
<p>This facility can also be used to create references between resources.
For example, we can create new drawable resources that are aliases for
existing images:</p>
<pre>
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;resources&gt;
&lt;drawable id=&quot;my_background&quot;&gt;&#64;android:drawable/theme2_background&lt;/drawable&gt;
&lt;/resources&gt;
</pre>
<a name="ReferencesToThemeAttributes"></a>
<h3>References to Theme Attributes</h3>
<p>Another kind of resource value allows you to reference the value of an
attribute in the current theme. This attribute reference can <em>only</em>
be used in style resources and XML attributes; it allows you to customize the
look of UI elements by changing them to standard variations supplied by the
current theme, instead of supplying more concrete values.</p>
<p>As an example, we can use this in our layout to set the text color to
one of the standard colors defined in the base system theme:</p>
<pre>
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;EditText id=&quot;text&quot;
xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
android:layout_width=&quot;fill_parent&quot; android:layout_height=&quot;fill_parent&quot;
<strong>android:textColor=&quot;?android:textDisabledColor&quot;</strong>
android:text=&quot;&#64;string/hello_world&quot; /&gt;
</pre>
<p>Note that this is very similar to a resource reference, except we are using
an '?' prefix instead of '@'. When you use this markup, you are supplying
the name of an attribute resource that will be looked up in the theme --
because the resource tool knows that an attribute resource is expected,
you do not need to explicitly state the type (which would be
<code>?android:attr/android:textDisabledColor</code>).</p>
<p>Other than using this resource identifier to find the value in the
theme instead of raw resources, the name syntax is identical to the '@' format:
<code>?[namespace:]type/name</code> with the type here being optional.</p>
<a name="UsingSystemResources"></a>
<h3>Using System Resources</h3>
<p>Many resources included with the system are available to applications.
All such resources are defined under the class "android.R". For example,
you can display the standard application icon in a screen with the following
code:</p>
<pre class="prettyprint">
public class MyActivity extends Activity
{
public void onStart()
{
requestScreenFeatures(FEATURE_BADGE_IMAGE);
super.onStart();
setBadgeResource(android.R.drawable.sym_def_app_icon);
}
}
</pre>
<p>In a similar way, this code will apply to your screen the standard
"green background" visual treatment defined by the system:</p>
<pre class="prettyprint">
public class MyActivity extends Activity
{
public void onStart()
{
super.onStart();
setTheme(android.R.style.Theme_Black);
}
}
</pre>
<a name="AlternateResources" id="AlternateResources"></a>
<h2>Alternate Resources (for alternate languages and configurations)</h2>
<p>You can supply different resources for your application to use depending on the UI
language or hardware configuration on the device. Note that although you can
include different string, layout, and other resources, the SDK does not expose
methods to let you specify which alternate resource set to load. Android
detects the proper set for the hardware and location, and loads them as
appropriate. Users can select alternate language settings using the settings
panel on the device. </p>
<p>To include alternate resources, create parallel resource folders with
qualifiers appended to the folder names, indicating the configuration it
applies to (language, screen orientation, and so on). For example, here is a
project that holds one string resource file for English, and another for
French:</p>
<pre>
MyApp/
res/
values-en/
strings.xml
values-fr/
strings.xml
</pre>
<p>Android supports several types of qualifiers, with various values for each.
Append these to the end of the resource folder name, separated by dashes. You
can add multiple qualifiers to each folder name, but they must appear in the
order they are listed here. For example, a folder containing drawable
resources for a fully specified configuration would look like this:</p>
<pre>
MyApp/
res/
drawable-en-rUS-large-long-port-mdpi-finger-keysexposed-qwerty-navexposed-dpad-480x320/
</pre>
<p>More typically, you will only specify a few specific configuration options. You may drop any of the values from the
complete list, as long as the remaining values are still in the same
order:</p>
<pre>
MyApp/
res/
drawable-en-rUS-finger/
drawable-port/
drawable-port-mdpi/
drawable-qwerty/
</pre>
<p>Table 2 lists the valid folder-name qualifiers, in order of precedence. Qualifiers that are listed higher in the table take precedence over those listed lower, as described in <a href="#best-match">How Android finds the best matching directory</a>. </p>
<p class="caption" id="table2">Table 2</p>
<table border="1">
<tr>
<th> Qualifier </th>
<th> Values </th>
</tr>
<tr>
<td>MCC and MNC</td>
<td><p>The mobile country code optionally followed by mobile network code
from the SIM in the device. For example
<code>mcc310</code> (U.S. on any carrier);
<code>mcc310-mnc004</code> (U.S., Verizon brand);
<code>mcc208-mnc00</code> (France, Orange brand);
<code>mcc234-mnc00</code> (U.K., BT brand).
</p><p>
If the device uses a radio connection (GSM phone), the MCC will come
from the SIM, and the MNC will come from the network to which the
device is attached. You might sometimes use the MCC alone, for example
to include country-specific legal resources in your application. If
your application specifies resources for a MCC/MNC combination, those
resources can only be used if both the MCC and the MNC match. </p></td>
</tr>
<tr>
<td>Language and region</td>
<td><p>The two letter <a href="http://www.loc.gov/standards/iso639-2/php/code_list.php">ISO
639-1</a> language code optionally followed by a two letter
<a href="http://www.iso.org/iso/en/prods-services/iso3166ma/02iso-3166-code-lists/list-en1.html">ISO
3166-1-alpha-2</a> region code (preceded by lowercase &quot;r&quot;). For example
<code>fr</code>, <code>en-rUS</code>, <code>fr-rFR</code>, <code>es-rES</code>.
</p><p>
The codes are <em>not</em> case-sensitive; the r prefix is used to
distinguish the region portion.
You cannot specify a region alone, but you can specify a language alone,
for example <code>en</code>, <code>fr</code>, <code>es</code>.</p> </td>
</tr>
<tr>
<td>Screen dimensions</td>
<td><p><code>small</code>, <code>normal</code>, <code>large</code>
</p><p>
Specify that the resource is for a particular class of screen.
The meanings of these are:</p>
<ul>
<li> <b>Normal screens</b> are based on the traditional Android HVGA
medium density screen. A screen is considered to be normal if it is
at least this size (independent of density) and not large. Examples
of such screens a WQVGA low density, HVGA medium density, WVGA
high density.
<li> <b>Small screens</b> are based on the space available on a
QVGA low density screen. Considering a portrait HVGA display, this has
the same available width but less height -- it is 3:4 vs. HVGA's
2:3 aspect ratio. Examples are QVGA low density and VGA high
density.
<li> <b>Large screens</b> are based on the space available on a
VGA medium density screen. Such a screen has significantly more
available space in both width and height than an HVGA display.
Examples are VGA and WVGA medium density screens.
</td>
</tr>
<tr>
<td>Wider/taller screens</td>
<td><p><code>long</code>, <code>notlong</code>
</p><p>
Specify that the resource is for a taller/wider than traditional
screen. This is based purely on the aspect ration of the screen:
QVGA, HVGA, and VGA are notlong; WQVGA, WVGA, FWVGA are long. Note
that long may mean either wide or tall, depending on the current
orientation.</p>
</td>
</tr>
<tr>
<td>Screen orientation</td>
<td><p><code>port</code>, <code>land</code>, <code>square</code>
</p><p>
Specifies that the resource is for a screen that is tall (port)
or wide (land); square is not currently used.</p>
</td>
</tr>
<tr>
<td>Screen pixel density</td>
<td><p><code>ldpi</code>, <code>mdpi</code>, <code>hdpi</code>, <code>nodpi</code>
</p><p>
Specifies the screen density the resource is defined for. The medium
density of traditional HVGA screens (mdpi) is defined to be approximately
160dpi; low density (ldpi) is 120, and high density (hdpi) is 240. There
is thus a 4:3 scaling factor between each density, so a 9x9 bitmap
in ldpi would be 12x12 is mdpi and 16x16 in hdpi. The special
<code>nodpi</code> density can be used with bitmap resources to prevent
them from being scaled at load time to match the device density.
</p><p>
When Android selects which resource files to use,
it handles screen density differently than the other qualifiers.
In step 1 of <a href="#best-match">How Android finds the best
matching directory</a> (below), screen density is always considered to
be a match. In step 4, if the qualifier being considered is screen
density, Android will select the best final match at that point,
without any need to move on to step 5.
</p><p>
You can also specify explicit densities like <code>92dpi</code>
or <code>108dpi</code>, but these are not fully supported by the
system so should not be used.
</p>
</td>
</tr>
<tr>
<td>Touchscreen type</td>
<td><code>notouch</code>, <code>stylus</code>, <code>finger</code></td>
</tr>
<tr>
<td>Whether the keyboard is available to the user</td>
<td><p><code>keysexposed</code>, <code>keyshidden</code>, <code>keyssoft</code>
</p><p>
If your application has specific resources that should only be used with a soft keyboard, use the <code>keyssoft</code> value. If no <code>keyssoft</code> resources are available (only <code>keysexposed</code> and <code>keyshidden</code>) and the device shows a soft keyboard, the system will use <code>keysexposed</code> resources.</p> </td>
</tr>
<tr>
<td>Primary text input method</td>
<td><code>nokeys</code>, <code>qwerty</code>, <code>12key</code> </td>
</tr>
<tr>
<td>Whether the navigation keys are available to the user</td>
<td><p><code>navexposed</code>, <code>navhidden</code>
</p><p>
If the hardware's navigation keys are currently available to
the user, the navexposed resources will be used; if they are not
available (such as behind a closed lid), navhidden will be used.</p></td>
</tr>
<tr>
<td>Primary non-touchscreen<br />
navigation method</td>
<td><code>nonav</code>, <code>dpad</code>, <code>trackball</code>, <code>wheel</code> </td>
</tr>
<tr>
<td>Screen dimensions</td>
<td><code>320x240</code>, <code>640x480</code>, etc. The larger dimension
must be specified first. This configuration is deprecated and
should not be used; use instead screen dimension, wider/taller
screens, and screen orientation described above.</td>
</tr>
<tr>
<td>SDK version</td>
<td>The SDK version supported by the device, for example <code>v3</code>. The Android 1.0 SDK is <code>v1, </code> the 1.1 SDK is <code>v2</code>, and the 1.5 SDK is <code>v3</code>.</td>
</tr>
<tr>
<td>(Minor version)</td>
<td>(You cannot currently specify minor version. It is always set to 0.)</td>
</tr>
</table>
<p>This list does not include device-specific parameters such as carrier,
branding, device/hardware, or manufacturer. Everything that an application
needs to know about the device that it is running on is encoded via the
resource qualifiers in the table above.</p>
<p>All resource directories, qualified and unqualified, live under the <code>res/</code> folder. Here are some guidelines on qualified resource directory names:</p>
<ul>
<li>You can specify multiple qualifiers, separated by dashes. For example, <code>drawable-en-rUS-land</code> will apply to US-English
devices in landscape orientation. </li>
<li>The qualifiers must be in the order listed in <a href="#table2">Table 2</a> above. For example:
<ul>
<li>Correct: <code>values-mcc460-nokeys/</code></li>
<li>Incorrect: <code>values-nokeys-mcc460/</code></li>
</ul>
</li>
<li>Values are case-insensitive. The resource compiler converts folder names
to lower case before processing to avoid problems in case-insensitive
file systems. On case-sensitive file systems, you should keep all names
lower-case or at least use a consistent case to protect your future
sanity when trying to find a resource file.</li>
<li>Only one value for each qualifier type is supported. For example, if you want to use exactly the same drawable files for Spain and France, you will need two resource directories, such as <code>drawable-rES/</code> and <code>drawable-rFR/</code>, containing identical files. You cannot
have a directory named <code>drawable-rES-rFR/</code>. </li>
<li>Qualified directories cannot be nested. For example, you cannot have <code>res/drawable/drawable-en</code>. </li>
</ul>
<h3>How resources are referenced in code</h3>
<p>All resources will be referenced in code or resource reference syntax by
their simple, undecorated names. So if a resource were named this:<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<code>MyApp/res/drawable-port-mdpi/myimage.png</code><br />
It would be referenced as this:<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<code>R.drawable.myimage</code> (code)<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<code>&#064;drawable/myimage</code> (XML)</p>
<p>If several drawable directories are available, Android will select one of them (as described below) and load <code>myimage.png</code> from it.</p>
<h3 id="best-match">How Android finds the best matching directory </h3>
<p>Android will pick which of the various underlying resource files should be
used at runtime, depending on the current configuration of the device.
The example used here assumes the following device configuration:</p>
<p style="margin-left:2em">Locale = <code>en-GB</code><br>
Screen orientation = <code>port</code><br>
Screen pixel density = <code>mdpi</code><br>
Touchscreen type = <code>notouch</code><br>
Primary text input method = <code>12key</code><br>
</p>
<p>Here is how Android makes the selection: </p>
<ol>
<li>
Eliminate resource files that contradict the
device configuration. For example, assume that the following resource directories are available for drawables. The <code>drawable-fr-rCA/</code> directory will be eliminated, because it contradicts the locale of the device.<br>
<pre>MyApp/res/drawable/
MyApp/res/drawable-en/
<strike>MyApp/res/drawable-fr-rCA/</strike>
MyApp/res/drawable-en-port/
MyApp/res/drawable-en-notouch-12key/
MyApp/res/drawable-port-ldpi/
MyApp/res/drawable-port-notouch-12key</pre>
<strong>Exception: </strong>Screen pixel density is the one qualifier that is not used to eliminate files. Even though the screen density of the device is medium dpi, <code>drawable-port-ldpi/</code> is not eliminated from the list, because every screen density is considered to be a
match at this point.</li>
<li>From <a href="#table2">Table 2</a>, pick the highest-precedence qualifier that remains in the list. (Start with MCC, then move down through the list.) </li>
<li>Do any of the available resource directories include this qualifier? </li>
<ul>
<li>If No, return to step 2 and look at the next qualifier listed in Table 2. In our example, the answer is &quot;no&quot; until we reach Language.</li>
<li>If Yes, move on to step 4.</li>
</ul>
<li>Eliminate resource directories that do not include this qualifier. In our example, we eliminate all the directories that do not include a language qualifier. </li>
<pre><strike>MyApp/res/drawable/</strike>
MyApp/res/drawable-en/
MyApp/res/drawable-en-port/
MyApp/res/drawable-en-notouch-12key/
<strike>MyApp/res/drawable-port-ldpi/</strike>
<strike>MyApp/res/drawable-port-notouch-12key</strike></pre>
<strong>Exception:</strong> If the qualifier in question is screen pixel density, Android will select the option that most closely matches the device, and the selection process will be complete. In general, Android will prefer scaling down a larger original image to scaling up a smaller original image.<br><br></li>
<li>Go back and repeat steps 2, 3, and 4 until only one choice remains. In the example, screen orientation is the next qualifier in the table for which we have any matches.
Eliminate resources that do not specify a screen orientation. </p>
<pre><strike>MyApp/res/drawable-en/</strike>
MyApp/res/drawable-en-port/
<strike>MyApp/res/drawable-en-notouch-12key/</strike></pre>
Only one choice remains, so that's it. When drawables are called for in this
example application, the Android system will load resources from the
<code>MyApp/res/drawable-en-port/</code> directory. In addition, if the
resource being loaded is a bitmap, it will be scaled up so that its supplied
low density matches the device's medium density.
</ol>
<p class="note"><strong>Tip:</strong> The <em>precedence</em> of the qualifiers is more important than the number of qualifiers that exactly match the device. For example, in step 4 above, the last choice on the list includes three qualifiers that exactly match the device (orientation, touchscreen type, and input method), while <code>drawable-en</code> has only one parameter that matches (language). However, language has a higher precedence, so <code>drawable-port-notouch-12key</code> is out.</p>
<p>This flowchart summarizes how Android selects resource directories to load.</p>
<p><img src="../../../images/resources/res-selection-flowchart.png" alt="resource-selection" width="461" height="471" style="margin:15px"></p>
<h3>Terminology</h3>
<p>The resource system brings a number of different pieces together to
form the final complete resource functionality. To help understand the
overall system, here are some brief definitions of the core concepts and
components you will encounter in using it:</p>
<p><strong>Asset</strong>: A single blob of data associated with an application. This
includes object files compiled from the Java source code, graphics (such as PNG
images), XML files, etc. These files are organized in a directory hierarchy
that, during final packaging of the application, is bundled together into a
single ZIP file.</p>
<p><strong>aapt</strong>: Android Asset Packaging Tool. The tool that generates the
final ZIP file of application assets. In addition to collecting raw assets
together, it also parses resource definitions into binary asset data.</p>
<p><strong>Resource Table</strong>: A special asset that aapt generates for you,
describing all of the resources contained in an application/package.
This file is accessed for you by the Resources class; it is not touched
directly by applications.</p>
<p><strong>Resource</strong>: An entry in the Resource Table describing a single
named value. Broadly, there are two types of resources: primitives and
bags.</p>
<p><strong>Resource Identifier</strong>: In the Resource Table all resources are
identified by a unique integer number. In source code (resource descriptions,
XML files, Java source code) you can use symbolic names that stand as constants for
the actual resource identifier integer.</p>
<p><strong>Primitive Resource</strong>: All primitive resources can be written as a
simple string, using formatting to describe a variety of primitive types
included in the resource system: integers, colors, strings, references to
other resources, etc. Complex resources, such as bitmaps and XML
describes, are stored as a primitive string resource whose value is the path
of the underlying Asset holding its actual data.</p>
<p><strong>Bag Resource</strong>: A special kind of resource entry that, instead of a
simple string, holds an arbitrary list of name/value pairs. Each name is
itself a resource identifier, and each value can hold
the same kinds of string formatted data as a normal resource. Bags also
support inheritance: a bag can inherit the values from another bag, selectively
replacing or extending them to generate its own contents.</p>
<p><strong>Kind</strong>: The resource kind is a way to organize resource identifiers
for various purposes. For example, drawable resources are used to
instantiate Drawable objects, so their data is a primitive resource containing
either a color constant or string path to a bitmap or XML asset. Other
common resource kinds are string (localized string primitives), color
(color primitives), layout (a string path to an XML asset describing a view
layout), and style (a bag resource describing user interface attributes).
There is also a standard "attr" resource kind, which defines the resource
identifiers to be used for naming bag items and XML attributes</p>
<p><strong>Style</strong>: The name of the resource kind containing bags that are used
to supply a set of user interface attributes. For example, a TextView class may
be given a style resource that defines its text size, color, and alignment.
In a layout XML file, you associate a style with a bag using the "style"
attribute, whose value is the name of the style resource.</p>
<p><strong>Style Class</strong>: Specifies a related set of attribute resources.
This data is not placed in the resource table itself, but used to generate
constants in the source code that make it easier for you to retrieve values out of
a style resource and/or XML tag's attributes. For example, the
Android platform defines a "View" style class that
contains all of the standard view attributes: padding, visibility,
background, etc.; when View is inflated it uses this style class to
retrieve those values from the XML file (at which point style and theme
information is applied as appropriate) and load them into its instance.</p>
<p><strong>Configuration</strong>: For any particular resource identifier, there may be
multiple different available values depending on the current configuration.
The configuration includes the locale (language and country), screen
orientation, etc. The current configuration is used to
select which resource values are in effect when the resource table is
loaded.</p>
<p><strong>Theme</strong>: A standard style resource that supplies global
attribute values for a particular context. For example, when writing an
Activity the application developer can select a standard theme to use, such
as the Theme.White or Theme.Black styles; this style supplies information
such as the screen background image/color, default text color, button style,
text editor style, text size, etc. When inflating a layout resource, most
values for widgets (the text color, selector, background) if not explicitly
set will come from the current theme; style and attribute
values supplied in the layout can also assign their value from explicitly
named values in the theme attributes if desired.</p>
<p><strong>Overlay</strong>: A resource table that does not define a new set of resources,
but instead replaces the values of resources that are in another resource table.
Like a configuration, this is applied at load time
to the resource data; it can add new configuration values (for example
strings in a new locale), replace existing values (for example change
the standard white background image to a "Hello Kitty" background image),
and modify resource bags (for example change the font size of the Theme.White
style to have an 18 pt font size). This is the facility that allows the
user to select between different global appearances of their device, or
download files with new appearances.</p>
<h2>Resource Reference</h2>
<p>The <a href="available-resources.html">Available Resources</a>
document provides a detailed list of the various types of resource and how to use them
from within the Java source code, or from other references.</p>
<a name="i18n" id="i18n"></a>
<h2>Internationalization and Localization</h2>
<p class="note"><strong>Coming Soon:</strong> Internationalization and Localization are
critical, but are also not quite ready yet in the current SDK. As the
SDK matures, this section will contain information on the Internationalization
and Localization features of the Android platform. In the meantime, it is a good
idea to start by externalizing all strings, and practicing good structure in
creating and using resources.</p>
<p><strong>This document has moved. Please see <a href="index.html">Application Resources</a>.</strong></p>

View File

@@ -0,0 +1,245 @@
page.title=Handling Runtime Changes
parent.title=Application Resources
parent.link=index.html
@jd:body
<div id="qv-wrapper">
<div id="qv">
<h2>In this document</h2>
<ol>
<li><a href="#CarryingAnObject">Carrying an Object During a Configuration Change</a></li>
<li><a href="#HandlingTheChange">Handling the Configuration Change Yourself</a>
</ol>
<h2>See also</h2>
<ol>
<li><a href="providing-resources.html">Providing Resources</a></li>
<li><a href="accessing-resources.html">Accessing Resources</a></li>
<li><a href="{@docRoot}resources/articles/faster-screen-orientation-change.html">Faster Screen
Orientation Change</a></li>
</ol>
</div>
</div>
<p>Some device configurations can change during runtime
(such as screen orientation, keyboard availability, and language). When such a change occurs,
Android's default behavior is to restart the running
Activity ({@link android.app.Activity#onDestroy()} is called, followed by {@link
android.app.Activity#onCreate(Bundle) onCreate()}). In doing so, the system re-queries your
application resources for alternatives that might apply to the new configuration.</p>
<p>It is important that your Activity safely handles restarts and restores its previous
state through the normal <a href="{@docRoot}guide/topics/fundamentals.html#lcycles">Activity
lifecycle</a>. In fact, it's a useful field test to invoke configuration changes (such as changing
the screen orientation) during various states of your application to be sure that it properly
restarts itself with the application state intact. So it's in the best interest of your application
to allow the system to restart your application during any configuration change&mdash;this behavior
is in place to help you by automatically handling configuration changes and adapting your
application as necessary.</p>
<p>However, you might encounter a situation in which restarting your application and
restoring significant amounts of data can be costly, create a slow user experience, and
using {@link android.app.Activity#onSaveInstanceState(Bundle) onSaveInstanceState()} does not
suffice. In such a situation, you have two options:</p>
<ol type="a">
<li><a href="#CarryingAnObject">Carrying an Object During a Configuration Change</a>
<p>Allow your
application to restart so that the appropriate configuration changes can take effect, but also
implement {@link android.app.Activity#onRetainNonConfigurationInstance()} paired with {@link
android.app.Activity#getLastNonConfigurationInstance()} to carry an {@link java.lang.Object} over
to the new instance of your Activity.</p>
<p>This is the recommended technique if you're facing performance issues during the
configuration restart. It allows your Activity to properly restart and reload resources for
the new configuration and also allows you to carry your arbitrary data that may be expensive to
collect again.</p>
</li>
<li><a href="#HandlingTheChange">Handling the Configuration Change Yourself</a>
<p>Declare that your
application will handle certain configuration changes and prevent the system from restarting your
application when such a change occurs. For example, you can declare in your manifest that your
Activity will handle configuration changes to the screen orientation. When the orientation
changes, your Activity will not be restarted and your Activity will receive a call to {@link
android.app.Activity#onConfigurationChanged(Configuration) onConfigurationChanged()} so that you can
perform necessary changes based on the new configuration.</p>
<p>This technique should be considered a last resort and temporary solution, because not all
runtime configuration changes can be handled this way&mdash;your application will eventually
encounter a runtime configuration in which you cannot prevent the Activity from being restarted,
whereas the first option will handle all configuration changes.</p>
</li>
</ol>
<p class="note"><strong>Note:</strong> Your application should always be able to successfully
restart at any time without any loss of user data or state in order to handle other events such as
when the user receives an incoming phone call and then returns to your application (read about the
<a href="{@docRoot}guide/topics/fundamentals.html#lcycles">Activity lifecycle</a>). The following
techniques for handling runtime configuration changes should only be necessary to optimize
performance during specific configuration changes.</p>
<h2 id="CarryingAnObject">Carrying an Object During a Configuration Change</h2>
<p>If your application has acquired significant amounts of data during its life, which would be
costly to recover due to a restart of the Activity, you can use {@link
android.app.Activity#onRetainNonConfigurationInstance()} paired with {@link
android.app.Activity#getLastNonConfigurationInstance()} to pass an {@link java.lang.Object}
to the new Activity instance. The {@link android.app.Activity#onRetainNonConfigurationInstance()}
method is called between {@link android.app.Activity#onStop()} and {@link
android.app.Activity#onDestroy()} when your Activity is being shut down due to a configuration
change. In your implementation of this method, you can return any {@link java.lang.Object} that you
need to efficiently restore your state after the configuration change. When your Activity is
created again, you can call {@link
android.app.Activity#getLastNonConfigurationInstance()} to retrieve the {@link
java.lang.Object}.</p>
<p>A scenario in which this can be valuable is if your application loads a lot of data from the
web. If the user changes the orientation of the device and the Activity restarts, your application
will need to re-fetch the data, which could be slow. What you can do is implement
{@link android.app.Activity#onRetainNonConfigurationInstance()} to return an object carrying your
data and then retrieve the data when your Activity restarts with {@link
android.app.Activity#getLastNonConfigurationInstance()}. For example:</p>
<pre>
&#64;Override
public Object onRetainNonConfigurationInstance() {
final MyDataObject data = collectMyLoadedData();
return data;
}
</pre>
<p class="caution"><strong>Caution:</strong> While you can return any object, you
should never pass an object that is tied to the {@link android.app.Activity}, such as a {@link
android.graphics.drawable.Drawable}, an {@link android.widget.Adapter}, a {@link android.view.View}
or any other object that's associated with a {@link android.content.Context}. If you do, it will
leak all the Views and resources of the original Activity instance. (To leak the resources
means that your application maintains a hold on them and they cannot be garbage-collected, so
lots of memory can be lost.)</p>
<p>Then get the {@code data} after the restart:</p>
<pre>
&#64;Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final MyDataObject data = (MyDataObject) getLastNonConfigurationInstance();
if (data == null) {
data = loadMyData();
}
...
}
</pre>
<p>In this case, {@link android.app.Activity#getLastNonConfigurationInstance()} is called to get
the data saved during the configuration change, and if it is null (which will happen if the
Activity is started in any case other than a configuration change) then the data is loaded
from the original source.</p>
<h2 id="HandlingTheChange">Handling the Configuration Change Yourself</h2>
<p>If your application doesn't need to update resources during a specific configuration
change <em>and</em> you have a performance limitation that requires you to
avoid the Activity restart, then you can declare that your Activity handles the configuration change
itself, which will prevent the system from restarting your Activity.</p>
<p class="note"><strong>Note:</strong> Handling the configuration change yourself can make it much
more difficult to use alternative resources, because the system will not automatically apply them
for you.</p>
<p>To declare that your Activity handles a configuration change, edit the appropriate <a
href="{@docRoot}guide/topics/manifest/activity-element.html">{@code &lt;activity&gt;}</a> element
in your manifest file to include the <a
href="{@docRoot}guide/topics/manifest/activity-element.html#config">{@code
android:configChanges}</a> attribute with a string value that represents the configuration that you
want to handle. Possible values are listed in the documentation for
the <a href="{@docRoot}guide/topics/manifest/activity-element.html#config">{@code
android:configChanges}</a> attribute (the most commonly used values are {@code orientation} to
handle when the screen orientation changes and {@code keyboardHidden} to handle when the
keyboard availability changes). You can declare multiple configuration values in the attribute
by separating them with a pipe character ("|").</p>
<p>For example, the following manifest snippet declares an Activity that handles both the
screen orientation change and keyboard availability change:</p>
<pre>
&lt;activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:label="@string/app_name">
</pre>
<p>Now when one of these configurations change, {@code MyActivity} is not restarted.
Instead, the Activity receives a call to {@link
android.app.Activity#onConfigurationChanged(Configuration) onConfigurationChanged()}. This method
is passed a {@link android.content.res.Configuration} object that specifies
the new device configuration. By reading fields in the {@link android.content.res.Configuration},
you can determine the new configuration and make appropriate changes by updating
the resources used in your interface. At the
time this method is called, your Activity's {@link android.content.res.Resources} object is updated
to return resources based on the new configuration, so you can easily
reset elements of your UI without the system restarting your Activity.</p>
<p>For example, the following {@link
android.app.Activity#onConfigurationChanged(Configuration) onConfigurationChanged()} implementation
checks the availability of a hardware keyboard and the current device orientation:</p>
<pre>
&#64;Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
}
// Checks whether a hardware keyboard is available
if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) {
Toast.makeText(this, "keyboard visible", Toast.LENGTH_SHORT).show();
} else if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES) {
Toast.makeText(this, "keyboard hidden", Toast.LENGTH_SHORT).show();
}
}
</pre>
<p>The {@link android.content.res.Configuration} object represents all of the current
configurations, not just the ones that have changed. Most of the time, you won't care exactly how
the configuration has changed and can simply re-assign all your resources that provide alternatives
to the configuration that you're handling. For example, because the {@link
android.content.res.Resources} object is now updated, you can reset
any {@link android.widget.ImageView}s with {@link android.widget.ImageView#setImageResource(int)}
and the appropriate resource for the new configuration is used (as described in <a
href="providing-resources.html#AlternateResources">Providing Resources</a>).</p>
<p>Notice that the values from the {@link
android.content.res.Configuration} fields are integers that are matched to specific constants
from the {@link android.content.res.Configuration} class. For documentation about which constants
to use with each field, refer to the appropriate field in the {@link
android.content.res.Configuration} reference.</p>
<p class="note"><strong>Remember:</strong> When you declare your Activity to handle a configuration
change, you are responsible for resetting any elements for which you provide alternatives. If you
declare your Activity to handle the orientation change and have images that should change
between landscape and portrait, you must re-assign each resource to each element during {@link
android.app.Activity#onConfigurationChanged(Configuration) onConfigurationChanged()}.</p>
<p>If you don't need to update your application based on these configuration
changes, you can instead <em>not</em> implement {@link
android.app.Activity#onConfigurationChanged(Configuration) onConfigurationChanged()}. In
which case, all of the resources used before the configuration change are still used
and you've only avoided the restart of your Activity. However, your application should always be
able to shutdown and restart with its previous state intact. Not only because
there are other configuration changes that you cannot prevent from restarting your application but
also in order to handle events such as when the user receives an incoming phone call and then
returns to your application.</p>
<p>For more about which configuration changes you can handle in your Activity, see the <a
href="{@docRoot}guide/topics/manifest/activity-element.html#config">{@code
android:configChanges}</a> documentation and the {@link android.content.res.Configuration}
class.</p>

View File

@@ -0,0 +1,444 @@
page.title=String Resources
parent.title=Resource Types
parent.link=available-resources.html
@jd:body
<p>A string resource provides text strings for your application
with optional text styling and formatting. There are three types of resources that can provide
your application with strings:</p>
<dl>
<dt><a href="#String">String</a></dt>
<dd>XML resource that provides a single string.</dd>
<dt><a href="#StringArray">String Array</a></dt>
<dd>XML resource that provides an array of strings.</dd>
<dt><a href="#Plurals">Plurals</a></dt>
<dd>XML resource that carries different strings for different pluralizations
of the same word or phrase.</dd>
</dl>
<p>All strings are capable of applying some styling markup and formatting arguments. For
information about styling and formatting strings, see the section about <a
href="#FormattingAndStyling">Formatting and Styling</a>.</p>
<h2 id="String">String</h2>
<p>A single string that can be referenced from the application or from other resource files (such
as an XML layout).</p>
<p class="note"><strong>Note:</strong> A string is a simple resource that is referenced
using the value provided in the {@code name} attribute (not the name of the XML file). So, you can
combine string resources with other simple resources in the one XML file,
under one {@code &lt;resources>} element.</p>
<dl class="xml">
<dt>file location:</dt>
<dd><code>res/values/<em>filename</em>.xml</code><br/>
The filename is arbitrary. The {@code &lt;string>} element's {@code name} will be used as the
resource ID.</dd>
<dt>compiled resource datatype:</dt>
<dd>Resource pointer to a {@link java.lang.String}.</dd>
<dt>resource reference:</dt>
<dd>
In Java: <code>R.string.<em>string_name</em></code><br/>
In XML:<code>@string/<em>string_name</em></code>
</dd>
<dt>syntax:</dt>
<dd>
<pre class="stx">
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;<a href="#string-resources-element">resources</a>>
&lt;<a href="#string-element">string</a>
name="<em>string_name</em>"
&gt;<em>text_string</em>&lt;/string&gt;
&lt;/resources>
</pre>
</dd>
<dt>elements:</dt>
<dd>
<dl class="tag-list">
<dt id="string-resources-element"><code>&lt;resources&gt;</code></dt>
<dd><strong>Required.</strong> This must be the root node.
<p>No attributes.</p>
</dd>
<dt id="string-element"><code>&lt;string&gt;</code></dt>
<dd>A string, which can include styling tags. Beware that you must escape apostrophes and
quotation marks. For more information about how to properly style and format your strings see <a
href="#FormattingAndStyling">Formatting and Styling</a>, below.
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>name</code></dt>
<dd><em>String</em>. A name for the string. This name will be used as the resource
ID.</dd>
</dl>
</dd>
</dl>
</dd> <!-- end elements and attributes -->
<dt>example:</dt>
<dd>XML file saved at <code>res/values/strings.xml</code>:
<pre>
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;resources>
&lt;string name="hello">Hello!&lt;/string>
&lt;/resources>
</pre>
<p>This layout XML applies a string to a View:</p>
<pre>
&lt;TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
<strong>android:text="@string/hello"</strong> />
</pre>
<p>This application code retrieves a string:</p>
<pre>
String string = {@link android.content.Context#getString(int) getString}(R.string.hello);
</pre>
<p>You can use either {@link android.content.Context#getString(int)} or
{@link android.content.Context#getText(int)} to retieve a string. {@link
android.content.Context#getText(int)} will retain any rich text styling applied to the string.</p>
</dd> <!-- end example -->
</dl>
<h2 id="StringArray">String Array</h2>
<p>An array of strings that can be referenced from the application.</p>
<p class="note"><strong>Note:</strong> A string array is a simple resource that is referenced
using the value provided in the {@code name} attribute (not the name of the XML file). As
such, you can combine string array resources with other simple resources in the one XML file,
under one {@code &lt;resources>} element.</p>
<dl class="xml">
<dt>file location:</dt>
<dd><code>res/values/<em>filename</em>.xml</code><br/>
The filename is arbitrary. The {@code &lt;string-array>} element's {@code name} will be used as the
resource ID.</dd>
<dt>compiled resource datatype:</dt>
<dd>Resource pointer to an array of {@link java.lang.String}s.</dd>
<dt>resource reference:</dt>
<dd>
In Java: <code>R.array.<em>string_array_name</em></code>
</dd>
<dt>syntax:</dt>
<dd>
<pre class="stx">
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;<a href="#string-array-resources-element">resources</a>>
&lt;<a href="#string-array-element">string-array</a>
name="<em>string_array_name</em>">
&lt;<a href="#string-array-item-element">item</a>
&gt;<em>text_string</em>&lt;/item&gt;
&lt;/string-array>
&lt;/resources>
</pre>
</dd>
<dt>elements:</dt>
<dd>
<dl class="tag-list">
<dt id="string-array-resources-element"><code>&lt;resources&gt;</code></dt>
<dd><strong>Required.</strong> This must be the root node.
<p>No attributes.</p>
</dd>
<dt id="string-array-element"><code>&lt;string-array&gt;</code></dt>
<dd>Defines an array of strings. Contains one or more {@code &lt;item>} elements.
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>name</code></dt>
<dd><em>String</em>. A name for the array. This name will be used as the resource
ID to reference the array.</dd>
</dl>
</dd>
<dt id="string-array-item-element"><code>&lt;item&gt;</code></dt>
<dd>A string, which can include styling tags. The value can be a referenced to another
string resource. Must be a child of a {@code &lt;string-array&gt;} element. Beware that you
must escape apostrophes and
quotation marks. See <a href="#FormattingAndStyling">Formatting and Styling</a>, below, for
information about to properly style and format your strings.
<p>No attributes.</p>
</dd>
</dl>
</dd> <!-- end elements -->
<dt>example:</dt>
<dd>XML file saved at <code>res/values/strings.xml</code>:
<pre>
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;resources>
&lt;string-array name="planets_array">
&lt;item>Mercury&lt;/item>
&lt;item>Venus&lt;/item>
&lt;item>Earth&lt;/item>
&lt;item>Mars&lt;/item>
&lt;/string-array>
&lt;/resources>
</pre>
<p>This application code retrieves a string array:</p>
<pre>
Resources res = {@link android.content.Context#getResources()};
String[] planets = res.{@link android.content.res.Resources#getStringArray(int)
getStringArray}(R.array.planets_array);
</pre>
</dd> <!-- end example -->
</dl>
<h2 id="Plurals">Plurals</h2>
<p>A pair of strings that each provide a different plural form of the same word or phrase,
which you can collectively reference from the application. When you request the plurals
resource using a method such as {@link android.content.res.Resources#getQuantityString(int,int)
getQuantityString()}, you must pass a "count", which will determine the plural form you
require and return that string to you.</p>
<p class="note"><strong>Note:</strong> A plurals collection is a simple resource that is
referenced using the value provided in the {@code name} attribute (not the name of the XML
file). As such, you can combine plurals resources with other simple resources in the one
XML file, under one {@code &lt;resources>} element.</p>
<dl class="xml">
<dt>file location:</dt>
<dd><code>res/values/<em>filename</em>.xml</code><br/>
The filename is arbitrary. The {@code &lt;plurals>} element's {@code name} will be used as the
resource ID.</dd>
<dt>resource reference:</dt>
<dd>
In Java: <code>R.plurals.<em>plural_name</em></code>
</dd>
<dt>syntax:</dt>
<dd>
<pre class="stx">
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;<a href="#plurals-resources-element">resources</a>>
&lt;<a href="#plurals-element">plurals</a>
name="<em>plural_name</em>">
&lt;<a href="#plurals-item-element">item</a>
quantity=["one" | "other"]
&gt;<em>text_string</em>&lt;/item>
&lt;/plurals>
&lt;/resources>
</pre>
</dd>
<dt>elements:</dt>
<dd>
<dl class="tag-list">
<dt id="plurals-resources-element"><code>&lt;resources&gt;</code></dt>
<dd><strong>Required.</strong> This must be the root node.
<p>No attributes.</p>
</dd>
<dt id="plurals-element"><code>&lt;plurals&gt;</code></dt>
<dd>A collection of strings, of which, one string is provided depending on the amount of
something. Contains one or more {@code &lt;item>} elements.
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>name</code></dt>
<dd><em>String</em>. A name for the pair of strings. This name will be used as the
resource ID.</dd>
</dl>
</dd>
<dt id="plurals-item-element"><code>&lt;item&gt;</code></dt>
<dd>A plural or singular string. The value can be a referenced to another
string resource. Must be a child of a {@code &lt;plurals&gt;} element. Beware that you must
escape apostrophes and quotation marks. See <a href="#FormattingAndStyling">Formatting and
Styling</a>, below, for information about to properly style and format your strings.
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>quantity</code></dt>
<dd><em>Keyword</em>. A value indicating the case in which this string should be used. Valid
values:
<table>
<tr><th>Value</th><th>Description</th></tr>
<tr>
<td>{@code one}</td><td>When there is one (a singular string).</td>
</tr>
<tr>
<td>{@code other}</td><td>When the quantity is anything other than one (a plural
string, but also used when the count is zero).</td>
</tr>
</table>
</dd>
</dl>
</dd>
</dl>
</dd> <!-- end elements -->
<dt>example:</dt>
<dd>XML file saved at {@code res/values/strings.xml}:</p>
<pre>
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;resources>
&lt;plurals name="numberOfSongsAvailable">
&lt;item quantity="one">One song found.&lt;/item>
&lt;item quantity="other">%d songs found.&lt;/item>
&lt;/plurals>
&lt;/resources>
</pre>
<p>Java code:</p>
<pre>
int count = getNumberOfsongsAvailable();
Resources res = {@link android.content.Context#getResources()};
String songsFound = res.{@link android.content.res.Resources#getQuantityString(int,int)
getQuantityString}(R.plurals.numberOfSongsAvailable, count);
</pre>
</dd> <!-- end example -->
</dl>
<h2 id="FormattingAndStyling">Formatting and Styling</h2>
<p>Here are a few important things you should know about how to properly
format and style your string resources.</p>
<h3>Escaping apostrophes and quotes</h3>
<p>If you have an apostrophe or a quote in your string, you must either escape it or enclose the
whole string in the other type of enclosing quotes. For example, here are some stings that
do and don't work:</p>
<pre>
&lt;string name="good_example">"This'll work"&lt;/string>
&lt;string name="good_example_2">This\'ll also work&lt;/string>
&lt;string name="bad_example">This doesn't work&lt;/string>
&lt;string name="bad_example_2">XML encodings don&amp;apos;t work&lt;/string>
</pre>
<h3>Formatting strings</h3>
<p>If you need to format your strings using <a
href="{@docRoot}reference/java/lang/String.html#format(java.lang.String,
java.lang.Object...)">{@code String.format(String, Object...)}</a>,
then you can do so by putting
your format arguments in the string resource. For example, with the following resource:</p>
<pre>
&lt;string name="welcome_messages">Hello, %1$s! You have %2$d new messages.&lt;/string>
</pre>
<p>In this example, the format string has two arguments: {@code %1$s} is a string and {@code %2$d}
is a decimal number. You can format the string with arguements from your application like this:</p>
<pre>
Resources res = {@link android.content.Context#getResources()};
String text = String.<a href="{@docRoot}reference/java/lang/String.html#format(java.lang.String,
java.lang.Object...)">format</a>(res.getString(R.string.welcome_messages), username, mailCount);
</pre>
<h3>Styling with HTML markup</h3>
<p>You can add styling to your strings with HTML markup. For example:</p>
<pre>
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;resources>
&lt;string name="welcome">Welcome to &lt;b>Android&lt;/b>!&lt;/string>
&lt;/resources>
</pre>
<p>Supported HTML elements include:</p>
<ul>
<li>{@code &lt;b>} for <b>bold</b> text.</li>
<li>{@code &lt;i>} for <i>italic</i> text.</li>
<li>{@code &lt;u>} for <u>underline</u> text.</li>
</ul>
<p>Sometimes you may want to create a styled text resource that is also used as a format
string. Normally, this won't work because the <a
href="{@docRoot}reference/java/lang/String.html#format(java.lang.String,
java.lang.Object...)">{@code String.format(String, Object...)}</a>
method will strip all the style
information from the string. The work-around to this is to write the HTML tags with escaped
entities, which are then recovered with {@link android.text.Html#fromHtml(String)},
after the formatting takes place. For example:</p>
<ol>
<li>Store your styled text resource as an HTML-escaped string:
<pre>
&lt;resources&gt;
&lt;string name="welcome_messages"&gt;Hello, %1$s! You have &amp;lt;b>%2$d new messages&amp;lt;/b>.&lt;/string>
&lt;/resources&gt;
</pre>
<p>In this formatted string, a {@code &lt;b>} element is added. Notice that the opening bracket is
HTML-escaped, using the {@code &amp;lt;} notation.</p>
</li>
<li>Then format the string as usual, but also call {@link android.text.Html#fromHtml} to
convert the HTML text into styled text:
<pre>
Resources res = {@link android.content.Context#getResources()};
String text = String.<a
href="{@docRoot}reference/java/lang/String.html#format(java.lang.String,
java.lang.Object...)">format</a>(res.getString(R.string.welcome_messages), username, mailCount);
CharSequence styledText = Html.fromHtml(text);
</pre>
</li>
</ol>
<p>Because the {@link android.text.Html#fromHtml} method will format all HTML entities, be sure to
escape any possible HTML characters in the strings you use with the formatted text, using
{@link android.text.TextUtils#htmlEncode}. For instance, if you'll be passing a string argument to
<a href="{@docRoot}reference/java/lang/String.html#format(java.lang.String,
java.lang.Object...)">{@code String.format()}</a> that may contain characters such as
"&lt;" or "&amp;", then they must be escaped before formatting, so that when the formatted string
is passed through {@link android.text.Html#fromHtml}, the characters come out the way they were
originally written. For example:</p>
<pre>
String escapedUsername = TextUtil.{@link android.text.TextUtils#htmlEncode htmlEncode}(username);
Resources res = {@link android.content.Context#getResources()};
String text = String.<a href="{@docRoot}reference/java/lang/String.html#format(java.lang.String,
java.lang.Object...)">format</a>(res.getString(R.string.welcome_messages), escapedUsername, mailCount);
CharSequence styledText = Html.fromHtml(text);
</pre>

View File

@@ -0,0 +1,128 @@
page.title=Style Resource
parent.title=Resource Types
parent.link=available-resources.html
@jd:body
<div id="qv-wrapper">
<div id="qv">
<h2>See also</h2>
<ol>
<li><a href="{@docRoot}guide/topics/ui/themes.html">Applying Styles and Themes</a></li>
</ol>
</div>
</div>
<p>A style resource defines the format and look for a UI.
A style can be applied to an individual {@link android.view.View} (from within a layout file) or to
an entire {@link android.app.Activity} or application (from within the manifest file).</p>
<p>For more information about creating and applying styles, please read
<a href="{@docRoot}guide/topics/ui/themes.html">Applying Styles and Themes</a>.</p>
<p class="note"><strong>Note:</strong> A style is a simple resource that is referenced
using the value provided in the {@code name} attribute (not the name of the XML file). As
such, you can combine style resources with other simple resources in the one XML file,
under one {@code &lt;resources>} element.</p>
<dl class="xml">
<dt>file location:</dt>
<dd><code>res/values/<em>filename</em>.xml</code><br/>
The filename is arbitrary. The element's {@code name} will be used as the resource ID.</dd>
<dt>resource reference:</dt>
<dd>
In XML: <code>@[package:]style/<em>style_name</em></code>
</dd>
<dt>syntax:</dt>
<dd>
<pre class="stx">
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;<a href="#resources-element">resources</a>>
&lt;<a href="#style-element">style</a>
name="<em>style_name</em>"
parent="@[package:]style/<em>style_to_inherit</em>">
&lt;<a href="#item-element">item</a>
name="<em>[package:]style_property_name</em>"
&gt;<em>style_value</em>&lt;/item>
&lt;/style>
&lt;/resources>
</pre>
</dd>
<dt>elements:</dt>
<dd>
<dl class="tag-list">
<dt id="resources-element"><code>&lt;resources&gt;</code></dt>
<dd><strong>Required.</strong> This must be the root node.
<p>No attributes.</p>
</dd>
<dt id="style-element"><code>&lt;style&gt;</code></dt>
<dd>Defines a single style. Contains {@code &lt;item&gt;} elements.
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>name</code></dt>
<dd><em>String</em>. <strong>Required</strong>. A name for the style, which is used as the
resource ID to apply the style to a View, Activity, or application.
</dd>
<dt><code>parent</code></dt>
<dd><em>Style resource</em>. Reference to a style from which this
style should inherit style properties.
</dd>
</dl>
</dd>
<dt id="item-element"><code>&lt;item&gt;</code></dt>
<dd>Defines a single property for the style. Must be a child of a
<code>&lt;style&gt;</code> element.</p>
<p class="caps">attributes:</p>
<dl class="atn-list">
<dt><code>name</code></dt>
<dd><em>Attribute resource</em>. <strong>Required</strong>. The name of the style property
to be defined, with a package prefix if necessary (for example {@code android:textColor}).
</dd>
</dl>
</dd>
</dl>
</dd> <!-- end elements and attributes -->
<dt>example:</dt>
<dd>
<dl>
<dt>XML file for the style (saved in <code>res/values/</code>):</dt>
<dd>
<pre>
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;resources>
&lt;style name="CustomText" parent="@style/Text">
&lt;item name="android:textSize">20sp&lt;/item>
&lt;item name="android:textColor">#008&lt;/item>
&lt;/style>
&lt;/resources>
</pre>
</dd>
<dt>XML file that applies the style to a {@link android.widget.TextView}
(saved in <code>res/layout/</code>):</dt>
<dd>
<pre>
&lt;?xml version="1.0" encoding="utf-8"?>
&lt;EditText
style="@style/CustomText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello, World!" />
</pre>
</dd>
</dl>
</dd> <!-- end example -->
</dl>

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB