package

android.content

Classes | Description

Contains classes for accessing and publishing data on the device. It includes three main categories of APIs: the Resources for retrieving resource data associated with an application; Content Providers and ContentResolver for managing and publishing persistent data associated with an application; and the Package Manager for finding out information about the application packages installed on the device.

In addition, the Context abstract class is a base API for pulling these pieces together, allowing you to access an application's resources and transfer data between applications.

This package builds on top of the lower-level Android packages android.database, android.text, android.graphics.drawable, android.graphics, android.os, and android.util.

  1. Resources
    1. Terminology
    2. Examples
      1. Using System Resources
      2. String Resources
      3. Color Resources
      4. Drawable Resources
      5. Layout Resources
      6. References to Resources
      7. References to Theme Attributes
      8. Style Resources
      9. Styles in Layout Resources

Resources

This topic includes a terminology list associated with resources, and a series of examples of using resources in code. For a complete guide on creating and using resources, see the document on Resources and Internationalization. For a reference on the supported Android resource types, see Available Resource Types.

The Android resource system keeps track of all non-code assets associated with an application. You use the Resources class to access your application's resources; the Resources instance associated with your application can generally be found through Context.getResources().

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, Java 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.

The rest of this section is organized as a tutorial on how to use resources in an application.

Terminology

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:

Asset: A single blob of data associated with an application. This includes Java object files, 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.

aapt: 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.

Resource Table: 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.

Resource: An entry in the Resource Table describing a single named value. Broadly, there are two types of resources: primitives and bags.

Resource Identifier: In the Resource Table all resources are identified by a unique integer number. In source code (resource descriptions, XML files, Java code) you can use symbolic names that stand as constants for the actual resource identifier integer.

Primitive Resource: 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.

Bag Resource: 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.

Kind: 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

Style: 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.

Style Class: Specifies a related set of attribute resources. This data is not placed in the resource table itself, but used to generate Java constants 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 approriate) and load them into its instance.

Configuration: 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, screen density, etc. The current configuration is used to select which resource values are in effect when the resource table is loaded.

Theme: A standard style resource that supplies global attribute values for a particular context. For example, when writing a 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.

Overlay: 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.

Examples

This section gives a few quick examples you can use to make your own resources. For more details on how to define and use resources, see Resources and Internationalization.

Using System Resources

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:

public class MyActivity extends Activity
{
    public void onStart() 
    {
        requestScreenFeatures(FEATURE_BADGE_IMAGE);

        super.onStart();

        setBadgeResource(android.R.drawable.sym_def_app_icon);
    }
}

In a similar way, this code will apply to your screen the standard "green background" visual treatment defined by the system:

public class MyActivity extends Activity
{
    public void onStart() 
    {
        super.onStart();

        setTheme(android.R.style.Theme_Black);
    }
}

String Resources

String resources are defined using an XML resource description syntax. The file or multiple files containing these resources can be given any name (as long as it has a .xml suffix) and placed at an appropriate location in the source tree for the desired configuration (locale/orientation/density).

Here is a simple resource file describing a few strings:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string id="mainLabel">Hello <u>th<ignore>e</ignore>re</u>, <i>you</i> <b>Activity</b>!</string>
    <string id="back">Back</string>
    <string id="clear">Clear</string>
</resources>

Typically this file will be called "strings.xml", and must be placed in the values directory:

MyApp/res/values/strings.xml

The strings can now be retrieved by your application through the symbol specified in the "id" attribute:

public class MyActivity extends Activity
{
    public void onStart() 
    {
        super.onStart();

        String back = getResources().getString(R.string.back).toString();
        back = getString(R.string.back).toString();  // synonym
    }
}

Unlike system resources, the resource symbol (the R class) we are using here comes from our own application's package, not android.R.

Note that the "mainLabel" string is complex, including style information. To support this, the getString() method returns a CharSequence object that you can pass to a TextView to retain those style. This is why code must call toString() on the returned resource if it wants a raw string.

Color Resources

Color resources are created in a way very similar to string resources, but with the <color> resource tag. The data for these resources must be a hex color constant of the form "#rgb", "#argb", "#rrggbb", or "#aarrggbb". The alpha channel is 0xff (or 0xf) for opaque and 0 for transparent.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color id="opaque_red">#ffff0000</color>
    <color id="transparent_red">#80ff0000</color>
    <color id="opaque_blue">#0000ff</color>
    <color id="opaque_green">#0f0</color>
</resources>

While color definitions could be placed in the same resource file as the previously shown string data, usually you will place the colors in their own file:

MyApp/res/values/colors.xml

The colors can now be retrieved by your application through the symbol specified in the "id" attribute:

public class MyActivity extends Activity
{
    public void onStart() 
    {
        super.onStart();

        int red = getResources().getColor(R.color.opaque_red);
    }
}

Drawable Resources

For simple drawable resources, all you need to do is place your image in a special resource sub-directory called "drawable". Files here are things that can be handled by an implementation of the Drawable class, often bitmaps (such as PNG images) but also various kinds of XML descriptions for selectors, gradients, etc.

The drawable files will be scanned by the resource tool, automatically generating a resource entry for each found. For example the file res/drawable/<myimage>.<ext> will result in a resource symbol named "myimage" (without the extension). Note that these file names must be valid Java identifiers, and should have only lower-case letters.

For example, to use your own custom image as a badge in a screen, you can place the image here:

MyApp/res/drawable/my_badge.png

The image can then be used in your code like this:

public class MyActivity extends Activity
{
    public void onStart() 
    {
        requestScreenFeatures(FEATURE_BADGE_IMAGE);

        super.onStart();

        setBadgeResource(R.drawable.my_badge);
    }
}

For drawables that are a single solid color, you can also define them in a resource file very much like colors shown previously. The only difference is that here we use the <drawable> tag to create a drawable resource.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <drawable id="opaque_red">#ffff0000</drawable>
    <drawable id="transparent_red">#80ff0000</drawable>
    <drawable id="opaque_blue">#0000ff</drawable>
    <drawable id="opaque_green">#0f0</drawable>
</resources>

These resource entries are often placed in the same resource file as color definitions:

MyApp/res/values/colors.xml

Layout Resources

Layout resources describe a view hierarchy configuration that is generated at runtime. These resources are XML files placed in the resource directory "layout", and are how you should create the content views inside of your screen (instead of creating them by hand) so that they can be themed, styled, configured, and overlayed.

Here is a simple layout resource consisting of a single view, a text editor:

<?xml version="1.0" encoding="utf-8"?>
<root>
    <EditText id="text"
        android:layout_width="fill-parent" android:layout_height="fill-parent"
        android:text="Hello, World!" />
</root>

To use this layout, it can be placed in a file like this:

MyApp/res/layout/my_layout.xml

The layout can then be instantiated in your screen like this:

public class MyActivity extends Activity
{
    public void onStart() 
    {
        super.onStart();
        setContentView(R.layout.my_layout);
    }
}

Note that there are a number of visual attributes that can be supplied to TextView (including textSize, textColor, and textStyle) that we did not define in the previous example; in such a sitation, the default values for those attributes come from the theme. If we want to customize them, we can supply them explicitly in the XML file:

<?xml version="1.0" encoding="utf-8"?>
<root>
    <EditText id="text"
        android:layout_width="fill_parent" android:layout_height="fill_parent"
        android:textSize="18" android:textColor="#008"
        android:text="Hello, World!" />
</root>

However, usually these kinds of attributes (those being attributes that usually make sense to vary with theme or overlay) should be defined through the theme or separate style resource. Later we will see how this is done.

References to Resources

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 do any resource type including colors and integers.

For example, if we have the previously defined color resources, we can write a layout file that sets the text color size to be the value contained in one of those resources:

<?xml version="1.0" encoding="utf-8"?>
<root>
    <EditText id="text"
        android:layout_width="fill_parent" android:layout_height="fill_parent"
        android:textColor="@color/opaque_red"
        android:text="Hello, World!" />
</root>

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 @[package:]type/name. 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:

<?xml version="1.0" encoding="utf-8"?>
<root>
    <EditText id="text"
        android:layout_width="fill_parent" android:layout_height="fill_parent"
        android:textColor="@android:color/opaque_red"
        android:text="Hello, World!" />
</root>

As another example, you should always use resource references when supplying strings in a layout file so that they can be localized:

<?xml version="1.0" encoding="utf-8"?>
<root>
    <EditText id="text"
        android:layout_width="fill_parent" android:layout_height="fill_parent"
        android:textColor="@android:color/opaque_red"
        android:text="@string/hello_world" />
</root>

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:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <drawable id="my_background">@android:drawable/theme2_background</drawable>
</resources>

References to Theme Attributes

Another kind of resource value allows you to reference the value of an attribute in the current theme. This attribute reference can only 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.

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:

<?xml version="1.0" encoding="utf-8"?>
<root>
    <EditText id="text"
        android:layout_width="fill_parent" android:layout_height="fill_parent"
        android:textColor="?android:textDisabledColor"
        android:text="@string/hello_world" />
</root>

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 ?android:attr/android:textDisabledColor).

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: ?[package:]type/name with the type here being optional.

Style Resources

A style resource is a set of name/value pairs describing a group of related attributes. There are two main uses for these resources: defining overall visual themes, and describing a set of visual attributes to apply to a class in a layout resource. In this section we will look at their use to describe themes; later we will look at using them in conjunction with layouts.

Like strings, styles are defined through a resource XML file. In the situation where we want to define a new theme, we can create a custom theme style that inherits from one of the standard system themes:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style id="Theme" parent="android:Theme.White">
        <item id="android:foregroundColor">#FFF8D96F</item>
        <item id="android:textColor">@color/opaque_blue</item>
        <item id="android:textSelectedColor">?android:textColor</item>
    </style>
</resources>

Typically these resource definitions will be placed in a file called "styles.xml" , and must be placed in the values directory:

MyApp/res/values/styles.xml

Similar to how we previously used a system style for an Activity theme, you can apply this style to your Activity:

public class MyActivity extends Activity
{
    public void onStart() 
    {
        super.onStart();

        setTheme(R.style.Theme);
    }
}

In the style resource shown here, we used the parent attribute to specify another style resource from which it inherits its values -- in this case the Theme.White system resource:

    <style id="Home" parent="android:Theme.White">
        ...
    </style>

Note, when doing this, that you must use the "android" prefix in front to tell the compiler the namespace to look in for the resource -- the resources you are specifying here are in your application's namespace, not the system. This explicit namespace specification ensures that names the application uses will not accidentally conflict with those defined by the system.

If you don't specify an explicit parent style, it will be inferred from the style name -- everything before the final '.' in the name of the style being defined is taken as the parent style name. Thus, to make another style in your application that inherits from this base Theme style, you can write:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style id="Theme.WhiteText">
        <item id="android:foregroundColor">#FFFFFFFF</item>
        <item id="android:textColor">?android:foregroundColor</item>
    </style>
</resources>

This results in the symbol R.style.Theme_WhiteText that can be used in Java just like we did with R.style.Theme above.

Styles in Layout Resources

Often you will have a number fo views in a layout that all use the same set of attributes, or want to allow resource overlays to modify the values of attributes. Style resources can be used for both of these purposes, to put attribute definitions in a single place that can be references by multiple XML tags and modified by overlays. To do this, you simply define a new style resource with the desired values:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style id="SpecialText">
        <item id="android:textSize">18</item>
        <item id="android:textColor">#008</item>
    </style>
</resources>

You can now apply this style to your TextView in the XML file:

<?xml version="1.0" encoding="utf-8"?>
<root>
    <EditText id="text1" style="@style/SpecialText"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:text="Hello, World!" />
    <EditText id="text2" style="@style/SpecialText"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:text="I love you all." />
</root>