Accessing resources from XML

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.

For example, if you add a Button to your layout, you should use a string resource for the button text:

Syntax

Here is the syntax to reference a resource in an XML resource:

·         <package_name> is the name of the package in which the resource is located (not required when referencing resources from the same 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

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 color resource and a string resource:

You can use these resources in the following layout file to set the text color and text string:

In this case you don't need to specify the package name in the resource reference because the resources are from your own package. To reference a system resource, you would need to include the package name. For example:

Note: 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 Providing alternative resources. For a complete guide to localizing your application for other languages,

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:

This sounds redundant, but can be very useful when using alternative resource.