Accessing Android resources

Android has a special folder called res, it make easily to accessing android resources. Using resources you can provide different characteristics to your application without modifying your code. Different dimensions, layouts, image sizes, languages, etc…

Accessing Android resources

Resource Types

The resource folder supports some special subdirectories.

Directory Resource Type
animator XML files that define property animations
anim XML files that define tween animations
color XML files that define a static list of colors
drawable Bitmap files (.png, .9.png, .jpg, .gif) or XML files
layout XML files that define a user interface layout
menu XML files that define application menus
raw Arbitrary files to save in their raw form
values XML files that contain simple values
xml Arbitrary XML files that can be read at runtime

See more: http://developer.android.com/guide/topics/resources/providing-resources.html#ResourceTypes

R.java

When you put a file in a resource folder, the ide will automatic add it to a special class named R (This class is auto generated. NEVER change it). By default it will create something like R.directory.filename (without extension), except for the files inside the folders values and color. For those the IDE will use the tags inside this file. For example:

In this case the IDE creates three entries on the R file: R.string.app_name, R.array.gender and R.dimen.app_padding

Accessing

XML

For accessing resources inside your XML you can use: @<resource_type>/<resource_name>

Java

For accessing resources inside your classes you can use: R.<resource_type>.<resource_name>
Some methods just expect a Resource Id to be provided, like:

Sometimes you need to get the content of your resource. Context and Activity have methods to access resources

For more details take a look at Android documentation page Accessing Resources or in this example app

About the author

Daniel Passos

Open source addicted, geek, teacher, traveler, Android and iOS freak. Android Tech Leader at Red Hat and Dj in spare time

By Daniel Passos

Categories

Tags