am c6cb8a78: docs: revisions to the new resources doc based on editorial feedback plus some fixes to resource references and other misc revisions

Merge commit 'c6cb8a78d03cda44a49a990b4d4153560bee7420' into froyo-plus-aosp

* commit 'c6cb8a78d03cda44a49a990b4d4153560bee7420':
  docs: revisions to the new resources doc based on editorial feedback
This commit is contained in:
Scott Main
2010-05-10 09:43:35 -07:00
committed by Android Git Automerger
10 changed files with 604 additions and 425 deletions

View File

@@ -22,12 +22,13 @@ parent.link=index.html
<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>
<li><a href="#ResourcesFromCode">Accessing Resources from Code</a></li>
<li><a href="#ResourcesFromXml">Accessing Resources from XML</a>
<ol>
<li><a href="#ReferencesToThemeAttributes">Referencing style attributes</a></li>
</ol>
</li>
<li><a href="#PlatformResources">Accessing Platform Resources</a></li>
</ol>
<h2>See also</h2>
@@ -39,154 +40,194 @@ parent.link=index.html
</div>
<p>There are two ways you can reference your resources for use in your application:</p>
<p>Once you provide a resource in your application (discussed in <a
href="providing-resources.html">Providing Resources</a>), you can apply it by
referencing its resource ID. All resource IDs are defined in your project's {@code R} class, which
the {@code aapt} tool automatically generates.</p>
<p>When your application is compiled, {@code aapt} generates the {@code R} class, which contains
resource IDs for all the resources in your {@code
res/} directory. For each type of resource, there is an {@code R} subclass (for example,
{@code R.drawable} for all drawable resources) and for each resource of that type, there is a static
integer (for example, {@code R.drawable.icon}). This integer is the resource ID that you can use
to retrieve your resource.</p>
<p>Although the {@code R} class is where resource IDs are specified, you should never need to
look there to discover a resource ID. A resource ID is always composed of:</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>The <em>resource type</em>: Each resource is grouped into a "type," such as {@code
string}, {@code drawable}, and {@code layout}. For more about the different types, see <a
href="available-resources.html">Resource Types</a>.
</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>The <em>resource name</em>, which is either: the filename,
excluding the extension; or the value in the XML {@code android:name} attribute, if the
resource is a simple value (such as a string).</li>
</ul>
<p>There are two ways you can access a resource:</p>
<ul>
<li><strong>In code:</strong> Using an static integer from a sub-class of your {@code R}
class, such as:
<pre class="classic no-pretty-print">R.string.hello</pre>
<p>{@code string} is the resource type and {@code hello} is the resource name. There are many
Android APIs that can access your resources when you provide a resource ID in this format. See
<a href="#ResourcesFromCode">Accessing Resources in Code</a>.</p>
</li>
<li><strong>In XML:</strong> Using a special XML syntax that also corresponds to
the resource ID defined in your {@code R} class, such as:
<pre class="classic no-pretty-print">&#64;string/hello</pre>
<p>{@code string} is the resource type and {@code hello} is the resource name. You can use this
syntax in an XML resource any place where a value is expected that you provide in a resource. See <a
href="#ResourcesFromXml">Accessing Resources from XML</a>.</p>
</li>
</ul>
<h2 id="ResourcesInCode">Accessing Resources in Code </h2>
<h2 id="ResourcesFromCode">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>
<p>You can use a resource in code by passing the resource ID as a method parameter. For
example, you can set an {@link android.widget.ImageView} to use the {@code res/drawable/myimage.png}
resource using {@link android.widget.ImageView#setImageResource(int) setImageResource()}:</p>
<pre>
ImageView imageView = (ImageView) findViewById(R.id.myimageview);
imageView.setImageResource(<strong>R.drawable.myimage</strong>);
</pre>
<p>You can also retrieve individual resources using methods in {@link
android.content.res.Resources}, which you can get an instance of
with {@link android.content.Context#getResources()}.</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
saving your files in {@code res/} won't work for you, because the only way to read a resource from
{@code res/} is with the resource ID. 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
<p>Files saved in the {@code assets/} directory are <em>not</em> 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>
android.content.res.Resources#openRawResource(int) openRawResource()}.</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>
<h3>Syntax</h3>
<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>
<p>Here's the syntax to reference a resource in code:</p>
<pre class="classic no-pretty-print">
[<em>&lt;package_name&gt;</em>.]R.<em>&lt;resource_type&gt;</em>.<em>&lt;resource_name&gt;</em>
</pre>
<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>
<li><em>{@code &lt;resource_name&gt;}</em> is either the resource filename
without the extension or the {@code android:name} attribute value in the XML element (for simple
values).</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>
<h3>Use cases</h3>
<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>There are many methods that accept a resource ID parameter and you can retrieve resources using
methods in {@link android.content.res.Resources}. You can get an instance of {@link
android.content.res.Resources} with {@link android.content.Context#getResources
Context.getResources()}.</p>
<p>Here are some examples of using resources in code:</p>
<p>Here are some examples of accessing 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) ;
setBackgroundDrawableResource}(<strong>R.drawable.my_background_image</strong>) ;
// 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));
getText}(<strong>R.string.main_title</strong>));
// Load a custom layout for the current screen
{@link android.app.Activity#setContentView(int)
setContentView}(R.layout.main_screen);
setContentView}(<strong>R.layout.main_screen</strong>);
// 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));
<strong>R.anim.hyperspace_in</strong>));
// 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);
TextView msgTextView = (TextView) findViewById(<strong>R.id.msg</strong>);
msgTextView.{@link android.widget.TextView#setText(int)
setText}(<strong>R.string.hello_message</strong>);
</pre>
<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 are overridden next time you compile.</p>
<h2 id="ResourcesFromXml">Accessing Resources from XML</h2>
<h2 id="ReferencesToResources">Accessing Resources in other XML Resources</h2>
<p>You can define values for some XML attributes and elements using a
reference to an existing resource. You will often do this when creating layout files, to
supply strings and images for your widgets.</p>
<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>For example, if you add a {@link android.widget.Button} to your layout, you should use
a <a href="string-resource.html">string resource</a> for the button text:</p>
<pre>
&lt;Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="<strong>@string/submit</strong>" /&gt;
</pre>
<h3>Syntax</h3>
<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>
<pre class="classic no-pretty-print">
&#64;[<em>&lt;package_name&gt;</em>:]<em>&lt;resource_type&gt;</em>/<em>&lt;resource_name&gt;</em>
</pre>
<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>
<li>{@code &lt;resource_name&gt;} is either the resource filename
without the extension or the {@code android:name} attribute value in the XML element (for simple
values).</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
<h3>Use cases</h3>
<p>In some cases you must use a resource for a value in XML (for example, to apply a drawable image
to a widget), but you can also use a resource in XML any place that accepts a simple value. 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>
@@ -206,8 +247,8 @@ text string:</p>
&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;
android:textColor=&quot;<strong>&#64;color/opaque_red</strong>&quot;
android:text=&quot;<strong>&#64;string/hello</strong>&quot; /&gt;
</pre>
<p>In this case you don't need to specify the package name in the resource reference because the
@@ -219,19 +260,18 @@ reference a system resource, you would need to include the package name. For exa
&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:textColor=&quot;<strong>&#64;android:color/secondary_text_dark</strong>&quot;
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
<p class="note"><strong>Note:</strong> You should use string resources at all times, so that your
application can be localized for other languages. 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>
<p>You can even use resources in XML to create aliases. For example, you can create a
drawable resource that is an alias for another drawable resource:</p>
<pre>
&lt;?xml version="1.0" encoding="utf-8"?>
@@ -239,15 +279,14 @@ image:</p>
android:src="@drawable/other_drawable" />
</pre>
<p>This is discussed further in <a href="providing-resources.html#AliasResources">Creating
alias resources</a>.</p>
<p>This sounds redundant, but can be very useful when using alternative resource. Read more about
<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
<p>A style attribute resource 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
@@ -257,28 +296,46 @@ essentially says, "use the style that is defined by this attribute, in the curre
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>
<pre class="classic">
?[<em>&lt;package_name&gt;</em>:][<em>&lt;resource_type&gt;</em>/]<em>&lt;resource_name&gt;</em>
</code>
</p>
</pre>
<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>
<p>For example, here's how you can reference an attribute 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:textColor=&quot;<strong>?android:textColorSecondary</strong>&quot;
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,
<p>Here, the {@code android:textColor} attribute specifies the name of a style attribute
in the current theme. Android now uses the value applied to the {@code android:textColorSecondary}
style attribute as the value for {@code android:textColor} in this widget. Because the system
resource tool knows that an attribute resource is expected in this context,
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>
<code>?android:attr/textColorSecondary</code>)&mdash;you can exclude the {@code attr} type.</p>
<h2 id="PlatformResources">Accessing Platform Resources</h2>
<p>Android contains a number of standard resources, such as styles, themes, and layouts. To
access these resource, qualify your resource reference with the
<code>android</code> package name. For example, Android provides a layout resource you can use for
list items in a {@link android.widget.ListAdapter}:</p>
<pre>
{@link android.app.ListActivity#setListAdapter(ListAdapter)
setListAdapter}(new {@link
android.widget.ArrayAdapter}&lt;String&gt;(this, <strong>android.R.layout.simple_list_item_1</strong>, myarray));
</pre>
<p>In this example, {@link android.R.layout#simple_list_item_1} is a layout resource defined by the
platform for items in a {@link android.widget.ListView}. You can use this instead of creating
your own layout for list items. (For more about using {@link android.widget.ListView}, see the
<a href="{@docRoot}resources/tutorials/views/hello-listview.html">List View Tutorial</a>.)</p>

View File

@@ -62,18 +62,18 @@ In XML: <code>@[<em>package</em>:]anim/<em>filename</em></code>
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;
android:pivotX="<em>float</em>"
android:pivotY="<em>float</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;
android:fromX="<em>float</em>"
android:toX="<em>float</em>"
android:fromY="<em>float</em>"
android:toY="<em>float</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;
android:pivotX="<em>float</em>"
android:pivotY="<em>float</em>" /&gt;
&lt;<a href="#set-element">set</a>&gt;
...
&lt;/set&gt;
@@ -158,21 +158,21 @@ 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>
<dd><em>Float or percentage</em>. Starting X offset. Expressed either: in pixels relative
to the normal position (such as {@code "5"}), in percentage relative to the element width (such as
{@code "5%"}), or in percentage relative to the parent width (such as {@code "5%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>
<dd><em>Float or percentage</em>. Ending X offset. Expressed either: in pixels relative
to the normal position (such as {@code "5"}), in percentage relative to the element width (such as
{@code "5%"}), or in percentage relative to the parent width (such as {@code "5%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>
<dd><em>Float or percentage</em>. Starting Y offset. Expressed either: in pixels relative
to the normal position (such as {@code "5"}), in percentage relative to the element height (such as
{@code "5%"}), or in percentage relative to the parent height (such as {@code "5%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>
<dd><em>Float or percentage</em>. Ending Y offset. Expressed either: in pixels relative
to the normal position (such as {@code "5"}), in percentage relative to the element height (such as
{@code "5%"}), or in percentage relative to the parent height (such as {@code "5%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
@@ -183,15 +183,19 @@ inherrited by this element).</p>
<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>
<dd><em>Float</em>. Starting angular position, in degrees.</dd>
<dt><code>android:toDegrees</code></dt>
<dd><em>Integer</em>. Ending angular position, in degrees.</dd>
<dd><em>Float</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>
<dd><em>Float or percentage</em>. The X coordinate of the center of rotation. Expressed
either: in pixels relative to the object's left edge (such as {@code "5"}), in percentage relative
to the object's left edge (such as {@code "5%"}), or in percentage relative to the parent
container's left edge (such as {@code "5%p"}).</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>
<dd><em>Float or percentage</em>. The Y coordinate of the center of rotation. Expressed
either: in pixels relative to the object's top edge (such as {@code "5"}), in percentage relative
to the object's top edge (such as {@code "5%"}), or in percentage relative to the parent
container's top edge (such as {@code "5%p"}).</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

View File

@@ -18,6 +18,23 @@ of application resource that you can provide in your resources directory ({@code
<p>Here's a brief summary of each resource type:</p>
<div class="sidebox-wrapper">
<div class="sidebox">
<h2>{@code R.id} Is Not a Resource</h2>
<p>You will often use an {@code R.id} integer to handle {@link android.view.View} objects in
your UI. Although the {@code id} is a subclass of the {@code R} class, it is not considered a
"resource" because it is not a reference to an externalized application resource. The {@code id}
is simply a unique identifier that allows you to handle elements in your UI by instantiating
objects with {@link android.app.Activity#findViewById(int) findViewById()}.</p>
<p>For information about using {@code R.id} with your UI, see <a
href="{@docRoot}guide/topics/ui/declaring-layout.html#attributes">Declaring Layout</a>.</p>
</div>
</div>
<dl>
<dt><a href="{@docRoot}guide/topics/resources/animation-resource.html">Animation Resources</a></dt>
<dd>Define pre-determined animations.<br/>

View File

@@ -463,11 +463,11 @@ In XML: <code>@[<em>package</em>:]drawable/<em>filename</em></code>
android:centerX="<em>integer</em>"
android:centerY="<em>integer</em>"
android:centerColor="<em>integer</em>"
android:endColor="<em>color</em>"
android:gradientRadius="<em>integer</em>"
android:type=""
android:usesLevel=""
android:startColor="<em>color</em>"
android:endColor="<em>color</em>" />
android:type=["linear" | "radial" | "sweep"]
android:usesLevel=["true" | "false"] />
&lt;<a href="#solid-element">solid</a>
android:color="<em>color</em>" />
&lt;<a href="#stroke-element">stroke</a>
@@ -544,18 +544,6 @@ a {@link android.graphics.drawable.LevelListDrawable}. This should normally be "
<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>
@@ -568,18 +556,30 @@ 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>
<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: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: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:useLevel</code></dt>
<dd><em>Boolean</em>. "true" if this is used as a {@link
android.graphics.drawable.LevelListDrawable}.</dd>
</dl>
</dd>
<dt id="solid-element"><code>&lt;solid&gt;</code></dt>

View File

@@ -27,14 +27,14 @@ important as more Android-powered devices become available with different config
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>
<div class="figure" style="width:441px">
<div class="figure" style="width:421px">
<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">
<div class="figure" style="width:421px">
<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

View File

@@ -36,14 +36,14 @@ In XML: <code>@[<em>package</em>:]layout/<em>filename</em></code>
&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;
android:layout_height=["<em>dimension</em>" | "fill_parent" | "wrap_content"]
android:layout_width=["<em>dimension</em>" | "fill_parent" | "wrap_content"]
[<em>ViewGroup-specific 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;
android:layout_height=["<em>dimension</em>" | "fill_parent" | "wrap_content"]
android:layout_width=["<em>dimension</em>" | "fill_parent" | "wrap_content"]
[<em>View-specific 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;

View File

@@ -35,12 +35,12 @@ In XML: <code>@[<em>package</em>:]menu.<em>filename</em></code>
<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>"
&lt;<a href="#item-element">item</a> android:id="@+id/<em>id_name</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:icon="@[package:]drawable/<em>drawable_resource_name</em>"
android:alphabeticShortcut="<em>string</em>"
android:numericShortcut="<em>string</em>"
android:checkable=["true" | "false"]
@@ -172,22 +172,22 @@ too long.</dd>
<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/item1"
android:title="@string/item1"
android:icon="@drawable/group_item1_icon" />
&lt;group android:id="@+id/group">
&lt;item android:id="@+id/group_item1"
android:title="Group Item 1"
android:icon="@drawable/example_item1_icon" />
android:title="@string/group_item1"
android:icon="@drawable/group_item1_icon" />
&lt;item android:id="@+id/group_item2"
android:title="Group Item 2"
android:icon="@drawable/example_item2_icon" />
android:title="G@string/group_item2"
android:icon="@drawable/group_item2_icon" />
&lt;/group>
&lt;item android:id="@+id/submenu"
android:title="Sub Menu" >
android:title="@string/submenu_title" >
&lt;menu>
&lt;item android:id="@+id/submenu_item"
android:title="Sub Menu Item" />
&lt;item android:id="@+id/submenu_item1"
android:title="@string/submenu_item1" />
&lt;/menu>
&lt;/item>
&lt;/menu>

View File

@@ -7,13 +7,15 @@ parent.link=index.html
<div id="qv">
<h2>Quickview</h2>
<ul>
<li>Different types of resources belong in different sub-directories of {@code res/}</li>
<li>Different types of resources belong in different subdirectories of {@code res/}</li>
<li>Alternative resources provide configuration-specific resource files</li>
</ul>
<h2>In this document</h2>
<ol>
<li><a href="#ResourceTypes">Grouping Resource Types</a></li>
<li><a href="#AlternativeResources">Providing Alternative Resources</a>
<ol>
<li><a href="#QualifierRules">Qualifier name rules</a></li>
<li><a href="#AliasResources">Creating alias resources</a></li>
</ol>
</li>
@@ -24,17 +26,30 @@ parent.link=index.html
<ol>
<li><a href="accessing-resources.html">Accessing Resources</a></li>
<li><a href="available-resources.html">Resource Types</a></li>
<li><a href="{@docRoot}guide/practices/screens_support.html">Supporting Multiple
Screens</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>You should always externalize application resources such as images and strings from your
code, so that you can maintain them independently. You can also provide alternative resources for
specific device configurations, by grouping them in specially-named resource directories. Android
will then automatically apply the appropriate resource based on the current configuration. For
instance, you might want to provide a different UI layout depending on the screen size.</p>
<p>For example, here's the file hierarchy for a simple project:</p>
<p>Once you save your resources external to your application code, you can access them
using resource IDs that are generated in your project's {@code R} class. How to use
resources in your application is discussed in <a href="accessing-resources.html">Accessing
Resources</a>.</p>
<pre class="no-pretty-print">
<h2 id="ResourceTypes">Grouping Resource Types</h2>
<p>You should place each type of resource in a specific subdirectory of your project's
{@code res/} directory. For example, here's the file hierarchy for a simple project:</p>
<pre class="classic no-pretty-print">
MyProject/
src/ <span style="color:black">
MyActivity.java </span>
@@ -42,23 +57,23 @@ MyProject/
drawable/ <span style="color:black">
icon.png </span>
layout/ <span style="color:black">
main_layout.xml </span>
main.xml
info.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>The {@code res/} directory contains all the resources (in subdirectories): an image resource, two
layout resources, and a string resource file. The resource directory names are important and are
described in table 1.</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>
<p class="table-caption" id="table1"><strong>Table 1.</strong> Resource directories
supported inside project {@code res/} directory.</p>
<table>
<tr>
<th scope="col">Directory</th>
<th scope="col">Resource Types</th>
<th scope="col">Resource Type</th>
</tr>
<tr>
@@ -70,13 +85,13 @@ href="animation-resource.html">Animation Resources</a>.</td>
<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>
State List Resource</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>
are compiled into the following drawable resource subtypes:</p>
<ul>
<li>Bitmap files</li>
<li>Nine-Patches (re-sizable bitmaps)</li>
@@ -107,37 +122,35 @@ Menu. See <a href="menu-resource.html">Menu Resource</a>.</td>
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>
<p>However, if you need access to original file names and file hierarchy, you might consider
saving some resources in the {@code
assets/} directory (instead of {@code res/raw/}). Files in {@code assets/} are not given a
resource ID, so you can read them only 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}
<p>Whereas XML resource files in other {@code res/} subdirectories define a single resource
based on the XML filename, files in the {@code values/} directory describe multiple resources.
For a file in this directory, each child of the {@code &lt;resources&gt;} element defines a single
resource. For example, a {@code &lt;string&gt;} element creates an
{@code R.string} resource and a {@code &lt;color&gt;} element creates 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>
<p>Because each resource is defined with its own XML element, you can name the file
whatever you want and place different resource types in one file. However, for clarity, you might
want to place unique resource types in different files. For example, here are some filename
conventions for resources you can create in this directory:</p>
<ul>
<li>arrays.xml to define resource arrays (<a
<li>arrays.xml for resource arrays (<a
href="more-resources.html#TypedArray">typed arrays</a>).</li>
<li>colors.xml to define <a
<li>colors.xml for <a
href="more-resources.html#Color">color values</a></li>
<li>dimens.xml to define <a
<li>dimens.xml for <a
href="more-resources.html#Dimension">dimension values</a>.</li>
<li>strings.xml to define <a href="string-resource.html">string
<li>strings.xml for <a href="string-resource.html">string
values</a>.</li>
<li>styles.xml to define <a href="style-resource.html">styles</a>.</li>
<li>styles.xml for <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
@@ -147,38 +160,42 @@ values</a>.</li>
<tr>
<td><code>xml/</code></td>
<td>Arbitrary XML files that are compiled and can be read at runtime by calling {@link
<td>Arbitrary XML files that 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
must 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 class="note"><strong>Note:</strong> You should never save resource files directly inside the
{@code res/} directory.</p>
<p>For more information about certain types of resources, see the <a
href="available-resources.html">Resource Types</a> documentation.</p>
<p>How to access resources in the {@code res/} subdirectories is discussed in <a
href="accessing-resources.html">Accessing Resources</a>.
</p>
<h2 id="AlternativeResources">Providing Alternative Resources</h2>
<div class="figure" style="width:441px">
<div class="figure" style="width:421px">
<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
configurations. For instance, you should include alternative drawable resources for different
screen densities and alternative string resources for different languages. At runtime, Android
automatically detects the current device configuration and loads the appropriate
resources.</p>
<p>For each set of resources for which you want to provide configuration-specific alternatives:</p>
<p>To specify configuration-specific alternatives for a set of resources:</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>}.
@@ -191,13 +208,13 @@ for which these resources are to be used.</li>
<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>
<li>Save your alternative resources in this new directory. The resource files must be 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">
<pre class="classic no-pretty-print">
res/
drawable/ <span style="color:black">
icon.png
@@ -207,22 +224,23 @@ res/
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
<p>The {@code hdpi} qualifier indicates that the resources in that directory are for devices with a
high-density screen. While the images in each drawable directory are sized for a specific screen
density, the filenames are
the same. This way, the resource ID that you use to reference the {@code icon.png} or {@code
background.png} image is always the same, but Android selects 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>
add multiple qualifiers to one directory name, by separating each qualifier with a dash. Table 2
lists the valid configuration qualifiers, in order of precedence&mdash;if you use multiple
qualifiers, they must be added to the directory name in the order 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">
<table>
<tr>
<th>Qualifier</th>
<th>Values</th>
@@ -237,18 +255,22 @@ names.</p>
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,
<p>The mobile country code (MCC), optionally followed by mobile network code (MNC)
from the SIM card 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>
<p>If the device uses a radio connection (GSM phone), the MCC comes
from the SIM, and the MNC comes from the network to which the
device is connected.</p>
<p>You can also use the MCC alone (for example, to include country-specific legal
resources in your application). If you need to specify based on the language only, then use the
<em>language and region</em> qualifier instead (discussed next). If you decide to use the MCC and
MNC qualifier, you should do so with care and test that it works as expected.</p>
<p>Also see the configuration fields {@link
android.content.res.Configuration#mcc}, and {@link
android.content.res.Configuration#mnc}, which indicate the current mobile country code
and mobile network code, respectively.</p>
</td>
</tr>
<tr>
<td>Language and region</td>
@@ -260,22 +282,24 @@ should do so with great care and completely test that it works as expected.</p><
<code>fr-rCA</code><br/>
etc.
</td>
<td><p>This is defined by a two-letter <a
<td><p>The language 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;).
3166-1-alpha-2</a> region code (preceded by lowercase &quot;{@code 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
of your application if the user changes his or her 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>
<p>Also see the {@link android.content.res.Configuration#locale} configuration field, which
indicates the current locale.</p>
</td>
</tr>
<tr>
@@ -286,24 +310,27 @@ your application for other langauges.</p>
<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
<ul class="nolist">
<li>{@code small}: Screens based on the space available on a
low-density QVGA screen. Considering a portrait HVGA display, this has
the same available width but less height&mdash;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
<li>{@code normal}: Screens based on the traditional
medium-density HVGA 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
<li>{@code large}: Screens based on the space available on a
medium-density VGA 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>
<p>Also see the {@link android.content.res.Configuration#screenLayout} configuration field,
which indicates whether the screen is small, normal,
or large.</p>
</td>
</tr>
<tr>
@@ -313,12 +340,14 @@ Screens</a> for more information.</p>
<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 class="nolist">
<li>{@code long}: Long screens, such as WQVGA, WVGA, FWVGA</li>
<li>{@code notlong}: Not long screens, such as QVGA, HVGA, and VGA</li>
</ul>
<p>This is not related to the screen orientation.</p>
<p>This is based purely on the aspect ratio of the screen (a "long" screen is wider). This
is not related to the screen orientation.</p>
<p>Also see the {@link android.content.res.Configuration#screenLayout} configuration field,
which indicates whether the screen is long.</p>
</td>
</tr>
<tr>
@@ -329,11 +358,16 @@ Screens</a> for more information.</p>
<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>
<ul class="nolist">
<li>{@code port}: Device is in portrait orientation (vertical)</li>
<li>{@code land}: Device is in landscape orientation (horizontal)</li>
<!-- Square mode is currently not used. -->
</ul>
<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>
<p>Also see the {@link android.content.res.Configuration#orientation} configuration field,
which indicates the current device orientation.</p>
</td>
</tr>
<tr>
@@ -343,12 +377,15 @@ how this affects your application during runtime.</p>
<code>desk</code>
</td>
<td>
<p>These configurations can be initiated when the device is placed in a dock.</p>
<ul class="nolist">
<li>{@code car}: Device is in a car dock</li>
<li>{@code desk}: Device is in a desk dock</li>
</ul>
<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>
dock. You can eneable or disable this mode using {@link
android.app.UiModeManager}. See <a href="runtime-changes.html">Handling Runtime Changes</a> for
information about how this affects your application during runtime.</p>
</td>
</tr>
<tr>
@@ -358,13 +395,16 @@ android.app.UiModeManager}.</p>
<code>notnight</code>
</td>
<td>
<p>
These configurations can be initiated by the device light sensor (if available).</p>
<ul class="nolist">
<li>{@code night}: Night time</li>
<li>{@code notnight}: Day time</li>
</ul>
<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>
<p>This can change during the life of your application if night mode is left in
auto mode (default), in which case the mode changes based on the time of day. You can eneable
or disable this mode using {@link android.app.UiModeManager}. See <a
href="runtime-changes.html">Handling Runtime Changes</a> for information about how this affects your
application during runtime.</p>
</td>
</tr>
<tr>
@@ -376,24 +416,27 @@ also explicitly set this mode using {@link android.app.UiModeManager}.</p>
<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.
<ul class="nolist">
<li>{@code ldpi}: Low-density screens; approximately 120dpi.</li>
<li>{@code mdpi}: Medium-density (on traditional HVGA) screens; approximately
160dpi.</li>
<li>{@code hdpi}: High-density screens; approximately 240dpi.</li>
<li>{@code nodpi}: This can be used for bitmap resources that you do not want to be scaled
to match the device density.</li>
</ul>
<p>There is thus a 4:3 scaling factor between each density, so a 9x9 bitmap
in ldpi is 12x12 in mdpi and 16x16 in hdpi.</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,
density, Android selects 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>
Screens</a> for more information about how to handle screen sizes and how Android might scale
your bitmaps.</p>
</td>
</tr>
<tr>
@@ -403,25 +446,45 @@ Screens</a> for more information.</p>
<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>
<ul class="nolist">
<li>{@code notouch}: Device does not have a touchscreen.</li>
<li>{@code stylus}: Device has a resistive touchscreen that's suited for use with a
stylus.</li>
<li>{@code finger}: Device has a touchscreen.</li>
</ul>
<p>Also see the {@link android.content.res.Configuration#touchscreen} configuration field,
which indicates the type of touchscreen on the device.</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>
<ul class="nolist">
<li>{@code keysexposed}: Device has a keyboard available. If the device has a
software keyboard enabled (which is likely), this may be used even when the hardware keyboard is
<em>not</em> exposed to the user, even if the device has no hardware keyboard. If no software
keyboard is provided or it's disabled, then this is only used when a hardware keyboard is
exposed.</li>
<li>{@code keyshidden}: Device has a hardware keyboard available but it is
hidden <em>and</em> the device does <em>not</em> have a software keyboard enabled.</li>
<li>{@code keyssoft}: Device has a software keyboard enabled, whether it's
visible or not.</li>
</ul>
<p>If you provide <code>keysexposed</code> resources, but not <code>keyssoft</code>
resources, the system uses the <code>keysexposed</code> resources regardless of whether a
keyboard is visible, as long as the system has a software keyboard enabled.</p>
<p>This can change during the life of your application if the user opens a hardware
keyboard. See <a href="runtime-changes.html">Handling Runtime Changes</a> for information about how
this affects your application during runtime.</p>
<p>Also see the configuration fields {@link
android.content.res.Configuration#hardKeyboardHidden} and {@link
android.content.res.Configuration#keyboardHidden}, which indicate the visibility of a hardware
keyboard and and the visibility of any kind of keyboard (including software), respectively.</p>
</td>
</tr>
<tr>
@@ -431,9 +494,17 @@ application during runtime.</p>
<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>
<td>
<ul class="nolist">
<li>{@code nokeys}: Device has no hardware keys for text input.</li>
<li>{@code qwert}: Device has a hardware qwerty keyboard, whether it's visible to the user
or not.</li>
<li>{@code 12key}: Device has a hardware 12-key keyboard, whether it's visible to the user
or not.</li>
</ul>
<p>Also see the {@link android.content.res.Configuration#keyboard} configuration field,
which indicates the primary text input method available.</p>
</td>
</tr>
<tr>
<td>Navigation key availability</td>
@@ -442,13 +513,16 @@ the {@code qwerty} resources.</td>
<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>
<ul class="nolist">
<li>{@code navexposed}: Navigation keys are available to the user.</li>
<li>{@code navhidden}: Navigation keys are not available (such as behind a closed
lid).</li>
</ul>
<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>
<p>Also see the {@link android.content.res.Configuration#navigationHidden} configuration
field, which indicates whether navigation keys are hidden.</p>
</td>
</tr>
<tr>
@@ -459,8 +533,16 @@ information about how this affects your application during runtime.</p>
<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>
<ul class="nolist">
<li>{@code nonav}: Device has no navigation facility other than using the
touchscreen.</li>
<li>{@code dpad}: Device has a directional-pad (d-pad) for navigation.</li>
<li>{@code trackball}: Device has a trackball for navigation.</li>
<li>{@code wheel}: Device has a directional wheel(s) for navigation (uncommon).</li>
</ul>
<p>Also see the {@link android.content.res.Configuration#navigation} configuration field,
which indicates the type of navigation method available.</p>
</td>
</tr>
<!-- DEPRECATED
@@ -495,20 +577,23 @@ about these values.</p>
</tr>
</table>
<p>Here are some important rules about using resource qualifier names:</p>
<h3 id="QualifierRules">Qualifier name rules</h3>
<p>Here are some 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
<li>The qualifiers must be in the order listed in <a href="#table2">table 2</a>. 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
<li>Alternative resource 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
@@ -517,36 +602,41 @@ example:
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>
However, you are not required to actually duplicate the same files in both locations. Instead, you
can create an alias to a resource. See <a href="#AliasResources">Creating
alias resources</a> below.</li>
</ul>
<p>After you save alternative resources into directories named with
these qualifiers, Android automatically applies the resources in your application based on the
current device configuration. Each time a resource is requested, Android checks for alternative
resource directories that contain the requested resource file, then <a href="#BestMatch">finds the
best-matching resource</a> (discussed below).</p>
<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
configuration (but not for all configurations), you do not need to put the same resource in
each alternative resource directory. 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
<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 do not offer this feature.</p>
<p>For example, imagine you have an application icon, {@code icon.png}, and need unique version of
it for different locales. However, two locales, English-Canadian and French-Canadian, need to
use the same version. You might assume that you need to copy the same image
into the resource directory for both English-Canadian and French-Canadian, but it's
not true. Instead, you can save the image that's used for both 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>
@@ -559,9 +649,10 @@ For example:</p>
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
<p>If you save this file as {@code icon.xml} (in an alternative resource directory, such as
{@code res/drawable-en-rCA/}), it is 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>
R.drawable.icon_ca} resource (which is saved in {@code res/drawable/}).</p>
<h4>Layout</h4>
@@ -576,7 +667,7 @@ element, wrapped in a {@code &lt;merge&gt;}. For example:</p>
&lt;/merge>
</pre>
<p>If you save this file as {@code main.xml}, it will be compiled into a resource you can reference
<p>If you save this file as {@code main.xml}, it is 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>
@@ -614,24 +705,24 @@ same way. For example, a color:</p>
<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>
<p>When you request a resource for which you provide alternatives, Android selects which
alternative resource to use at runtime, depending on the current device configuration. To
demonstrate how Android selects an alternative resource, assume the following drawable directories
each contain different versions of the same images:</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 class="classic no-pretty-print">
drawable/
drawable-en/
drawable-fr-rCA/
drawable-en-port/
drawable-en-notouch-12key/
drawable-port-ldpi/
drawable-port-notouch-12key/
</pre>
<p>And assume the following is the device configuration:</p>
<p style="margin-left:2em;">
<p style="margin-left:1em;">
Locale = <code>en-GB</code> <br/>
Screen orientation = <code>port</code> <br/>
Screen pixel density = <code>hdpi</code> <br/>
@@ -639,85 +730,93 @@ Touchscreen type = <code>notouch</code> <br/>
Primary text input method = <code>12key</code>
</p>
<p>By comparing the device configuration to the available alternative resources, Android selects
drawables from {@code drawable-en-port}. It arrives at this decision using the following logic:</p>
<div class="figure" style="width:280px">
<img src="{@docRoot}images/resources/res-selection-flowchart.png" alt="" height="590" />
<p class="img-caption"><strong>Figure 2.</strong> Flowchart of how Android finds the
best-matching resource.</p>
</div>
<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">
<p>The <code>drawable-fr-rCA/</code> directory is eliminated, because it
contradicts the <code>en-GB</code> locale.</p>
<pre class="classic 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
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,
<p class="note"><strong>Exception:</strong> Screen pixel density is the one qualifier that is not
eliminated due to a contradiction. 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>
considered to be a match at this point. More information is available in the <a
href="{@docRoot}guide/practices/screens_support.html">Supporting Multiple
Screens</a> document.</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>
<li>Pick the (next) highest-precedence qualifier in the list (<a href="#table2">table 2</a>).
(Start with MCC, then move down.) </li>
<li>Do any of the 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>
<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, continue 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">
<pre class="classic 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>
<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>
Android
selects the option that most closely matches the device, and the selection process is complete.
In general, Android prefers scaling down a larger original image to scaling up a smaller
original image. See <a href="{@docRoot}guide/practices/screens_support.html">Supporting Multiple
Screens</a>.</p>
</li>
<li>Go back and repeat steps 2, 3, and 4 until only one choice remains. In the example, screen
<li>Go back and repeat steps 2, 3, and 4 until only one directory 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">
<pre class="classic 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>
<p>The remaining directory is {@code drawable-en-port}.</p>
</li>
</ol>
<p>Though this procedure is executed for each resource requested, the system will further optimize
<p>Though this procedure is executed for each resource requested, the system further optimizes
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
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
something other than English is never 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
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>
<code>drawable-port-notouch-12key</code> is out.</p>
<p>To learn more about how to use resources in your application, continue to <a
href="accessing-resources.html">Accessing Resources</a>.</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

@@ -8,7 +8,7 @@ parent.link=index.html
<h2>In this document</h2>
<ol>
<li><a href="#CarryingAnObject">Carrying an Object During a Configuration Change</a></li>
<li><a href="#RetainingAnObject">Retaining an Object During a Configuration Change</a></li>
<li><a href="#HandlingTheChange">Handling the Configuration Change Yourself</a>
</ol>
@@ -24,80 +24,80 @@ Orientation Change</a></li>
<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
Android restarts 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>
android.app.Activity#onCreate(Bundle) onCreate()}). The restart behavior is designed to help your
application adapt to new configurations by automatically reloading your application with
alternative resources.</p>
<p>It is important that your Activity safely handles restarts and restores its previous
<p>To properly handle a restart, it is important that your Activity 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>
lifecycle</a>, in which Android calls
{@link android.app.Activity#onSaveInstanceState(Bundle) onSaveInstanceState()} before it destroys
your Activity so that you can save data about the application state. You can then restore the state
during {@link android.app.Activity#onCreate(Bundle) onCreate()} or {@link
android.app.Activity#onRestoreInstanceState(Bundle) onRestoreInstanceState()}. To test
that your application restarts itself with the application state intact, you should
invoke configuration changes (such as changing the screen orientation) while performing various
tasks in your application.</p>
<p>Your application should be able to restart at any time without loss of user data or
state in order to handle 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>).</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>
restoring significant amounts of data can be costly and create a poor user experience. 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><a href="#RetainAnObject">Retain an object during a configuration change</a>
<p>Allow your Activity to restart when a configuration changes, but carry a stateful
{@link java.lang.Object} to the new instance of your Activity.</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><a href="#HandlingTheChange">Handle the configuration change yourself</a>
<p>Prevent the system from restarting your Activity during certain configuration
changes and receive a callback when the configurations do change, so that you can manually update
your Activity as necessary.</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="RetainingAnObject">Retaining an Object During a Configuration Change</h2>
<h2 id="CarryingAnObject">Carrying an Object During a Configuration Change</h2>
<p>If restarting your Activity requires that you recover large sets of data, re-establish a
network connection, or perform other intensive operations, then a full restart due to a
configuration change might
be an unpleasant user experience. Also, it may not be possible for you to completely
maintain your Activity state with the {@link android.os.Bundle} that the system saves for you during
the Activity lifecycle&mdash;it is not designed to carry large objects (such as bitmaps) and the
data within it must be serialized then deserialized, which can consume a lot of memory and make the
configuration change slow. In such a situation, you can alleviate the burden of reinitializing
your Activity by retaining a stateful Object when your Activity is restarted due to a configuration
change.</p>
<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>To retain an Object during a runtime configuration change:</p>
<ol>
<li>Override the {@link android.app.Activity#onRetainNonConfigurationInstance()} method to return
the Object you would like to retain.</li>
<li>When your Activity is created again, call {@link
android.app.Activity#getLastNonConfigurationInstance()} to recover your Object.</li>
</ol>
<p>Android calls {@link android.app.Activity#onRetainNonConfigurationInstance()} between {@link
android.app.Activity#onStop()} and {@link
android.app.Activity#onDestroy()} when it shuts down your Activity due to a configuration
change. In your implementation of {@link
android.app.Activity#onRetainNonConfigurationInstance()}, you can return any {@link
java.lang.Object} that you need in order to efficiently restore your state after the configuration
change.</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
must re-fetch the data, which could be slow. What you can do instead 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
data and then retrieve the data when your Activity starts again with {@link
android.app.Activity#getLastNonConfigurationInstance()}. For example:</p>
<pre>
@@ -116,7 +116,7 @@ leak all the Views and resources of the original Activity instance. (To leak the
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>
<p>Then retrieve the {@code data} when your Activity starts again:</p>
<pre>
&#64;Override
@@ -132,9 +132,10 @@ public void onCreate(Bundle savedInstanceState) {
}
</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
<p>In this case, {@link android.app.Activity#getLastNonConfigurationInstance()} retrieves
the data saved by {@link android.app.Activity#onRetainNonConfigurationInstance()}. If {@code data}
is null (which happens when the
Activity starts due to any reason other than a configuration change) then the data object is loaded
from the original source.</p>
@@ -146,11 +147,12 @@ from the original source.</p>
<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>
itself, which prevents 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>
more difficult to use alternative resources, because the system does not automatically apply them
for you. This technique should be considered a last resort and is not recommended for most
applications.</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

BIN
docs/html/images/resources/res-selection-flowchart.png Executable file → Normal file

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

After

Width:  |  Height:  |  Size: 32 KiB