Accessing your app resources

Once you provide a resource in your application, you can apply it by referencing its resource ID. All resource IDs are defined in your project's R class, which the aapt tool automatically generates.

When your application is compiled, aapt generates the R class, which contains resource IDs for all the resources in your res/ directory. For each type of resource, there is an R subclass (for example, R.drawable for all drawable resources), and for each resource of that type, there is a static integer (for example, R.drawable.icon). This integer is the resource ID that you can use to retrieve your resource.

Although the 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:

·         The resource type: Each resource is grouped into a "type," such as stringdrawable, and layout.

·         The resource name, which is either: the filename, excluding the extension; or the value in the XML android:nameattribute, if the resource is a simple value (such as a string).

There are two ways you can access a resource:

·         In code: Using a static integer from a sub-class of your R class, such as:

string is the resource type and hello is the resource name. There are many Android APIs that can access your resources when you provide a resource ID in this format.

In XML: Using a special XML syntax that also corresponds to the resource ID defined in your R class, such as:

Accessing resources in code

You can use a resource in code by passing the resource ID as a method parameter. For example, you can set an ImageView to use the res/drawable/myimage.webp resource using setImageResource():

You can also retrieve individual resources using methods in Resources, which you can get an instance of with getResources().

Syntax

Here's the syntax to reference a resource in code:

[<package_name>.]R.<resource_type>.<resource_name>

·         <package_name> is the name of the package in which the resource is located (not required when referencing resources from your own package).

·         <resource_type> is the R subclass for the resource type.

·         <resource_name> is either the resource filename without the extension or the android:name attribute value in the XML element (for simple values).

Use cases

There are many methods that accept a resource ID parameter and you can retrieve resources using methods in Resources. You can get an instance of Resources with Context.getResources().

Here are some examples of accessing resources in code:

Caution: You should never modify the R.java file by hand—it is generated by the aapt tool when your project is compiled. Any changes are overridden next time you compile.