Accessing resources

Once you provide a resource in your application (discussed in Providing Resources), it is assigned a resource ID.

There are two types of resources:

  • File resources (layout, image, style, background, TTF font)
  • XML resource values (string, color, dimen, bool, XML font)

Accessing Resources in XML

Accessing an image

Images are provided as file resources. They are located in image group folders. As an example, if we provided the following image:

res/
  image/
    myImage.png

To reference it from a xml file (like a layout file), one can use the syntax @image/myImage. It is composed of the @image/ prefix, followed by the name of the image file.

For instance, to set the image as the background of a TextLabel, simply write in the XML layout file:

<TextLabel backgroundImage="@image/myImage" />

Accessing a color

If a color is declared in res/values/colors.xml that contains the following:

<color name="myColor">#ff0000</color>

The color resource can be accessed with the following notation:

<TextLabel backgroundColor="@color/myColor"

Special case of ID

Warning: two notations related to IDs are very similar but do not have the same meanings!

@id/id_name will access the ID resource (Res.id.id_name). This is a reference to an already declared ID.

@+id/id_name (notice the``+`` sign) will create the resource identifier with the name id_name and access it. The + character means that this is an ID creation.

Accessing Resources in Code

To access a resource from code, the com.neomades.app.ResManager class is the only place to look at. It provides several utility methods to access each type of resource.

For all the resources declared in the project, the Res.java class generated in the main package of the application contains a constant field representing each resource.

For example, an image declared in res/image/image_name.png will be accessible with:

Image image = ResManager.getImage(Res.image.image_name);

A constant field generated in Res.java is named after the physical name of a resource.

Accessing Strings in Code

String resources can be declared as follows:

<string name="string_name">My String value</string>

This string resource can then be accessed with:

String string = ResManager.getString(Res.string.string_name);

Accessing Assets in Code

An asset that is declared in assets/my_asset.ext can be opened with the following statement:

InputStream assetStream = ResManager.openAsset("my_asset.ext");