Resources are the additional files and static content that your code uses, such as bitmaps, layout definitions, user interface strings, animation instructions, and more.
You should always externalize resources such as images and strings from your application code, so that you can maintain them independently. Externalizing your resources also allows you to provide alternative resources that support specific device configurations such as different languages or screen sizes, which becomes increasingly important as more Android-powered devices become available with different configurations. In order to provide compatibility with different configurations, you must organize resources in your project's res/
directory, using various sub-directories that group resources by type and configuration.
Here's a brief summary of each resource type:
res/anim/
and accessed from the R.anim
class. Frame animations are saved in res/drawable/
and accessed from the R.drawable
class.res/color/
and accessed from the R.color
class.res/drawable/
and accessed from the R.drawable
class.res/layout/
and accessed from the R.layout
class.res/menu/
and accessed from the R.menu
class.res/values/
and accessed from the R.string
, R.array
, and R.plurals
classes.res/values/
and accessed from the R.style
class.res/font/
and accessed from the R.font
class.res/values/
but each accessed from unique R sub-classes (such as R.bool
, R.integer
, R.dimen
, etc.).String Resources
A string resource provides text strings for your application with optional text styling and formatting. There are three types of resources that can provide your application with strings:
To allow the app using formatted strings from resources you can use following snippet
<string name="app_ver">SuperApp, ver. %1$d</string>
and in code
String ver = getResources().getString(R.string.app_ver, 7);
How to use float value in dimen resource type
Declare in dimen.xml
<resources> <item name="my_float_value" type="dimen" format="float">7.34</item> </resources>
Referencing from xml
@dimen/my_float_value
Referencing from java
TypedValue typedValue = new TypedValue(); getResources().getValue(R.dimen.my_float_value, typedValue, true); float myFloatValue = typedValue.getFloat();
How to use integer value in dimen resource type
Declare in res/values/integers.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <integer name="max_speed">75</integer> <integer name="min_speed">5</integer> </resources>
This application code retrieves an integer:
int maxSpeed = getResources().getInteger(R.integer.max_speed);
How to get resource by name
public static Drawable getDrawable(Context context, String name) { int resourceId = context.getResources().getIdentifier(name, "drawable", context.getPackageName()); return context.getResources().getDrawable(resourceId); }