Click here to Skip to main content
Click here to Skip to main content
Go to top

Article 6 - Beginner’s Guide to Organizing/Accessing Android Resources

, 25 Aug 2014
Rate this:
Please Sign up or sign in to vote.
A complete beginners guide to organizing and accessing android resources. Starts from basics and covers all aspects with regards to defining, using and following the best practices etc.

Introduction

In this article let us try understand in detail about Andorid Resources. 

The following topics are covered 

Background

Please find the below link for "Introduction to Android"

http://www.codeproject.com/Articles/802449/Article-Introduction-to-Android
 

Please refer the below mentioned article to setup your development environment.

http://www.codeproject.com/Articles/803609/Article-Setting-Up-Your-Android-Development-Enviro
 

What are resources and what are they used for?

Whenever you are creating an android application, you will notice that in addition to the source files, you will also see various other static files for images (for different screen sizes), audio, video, xml files such as string.xml, color.xml to name some of them. All of these static files which are non-code files are known as resources. We will be shortly seeing in details about all these resource files. 
When you are building your application, these static files also gets compiled and included as a part of the application and package with the APK file for distribution. 

Here’s what the resources are used for and its advantages 
The resource files can be used for managing various static resources that the application is making use off. Every resource files will reside under a dedicated resource folder with the root folder – ‘res’. For example, if you have navigated to values folder, you will see a dedicated resource files for managing various resources such as

•    arrays.xml – Used for managing the resource arrays (typed arrays).
•    colors.xml – Used for color values
•    dimens.xml – Used for dimension values.
•    strings.xml – Used for managing string values.
•    styles.xml - Used for application styles.

Similarly you can see other folders such as ‘xml’ used for maintaining the configuration files, drawable folders for managing all your image files. Among these resource folders, there’s one most important one is the layout folder, which holds the activity layout xml files. Each of these layout files separates the view (UI) from the activity code.  

1. Resource files are used to separate and maintain them independently from the application code. Take an example of a string resource were you can have all the string values, array of string etc that you are using within your application code or layout files. You will have a better control in maintaining at single location which you can reuse them in one more layout xml files or you can access the same within your application. Also if there’s any change required, instead of looking into multiple places you have a common dedicated files for handling all your resources.  

2. When you are externalizing the resources, you have an option of providing an alternative resource for various device configurations with different screen sizes or languages.  

Best practices for organizing various resources

Let us now see the best practices for organizing all the resources that the application can make use of. 

Colors

It’s recommended to define all references to colors within your application in color.xml. You can create a new value resource file under “res/values” and name it as “color.xml”.  Note - You can have only color xml file per application. 

Here’s a cool website which you can use to build the color values http://redinput.com/colors/. The Colors can be defined in the following formats only. 

•    #RGB
•    #ARGB
•    #RRGGBB
•    #AARRGGBB

The color values can be used in places were a property accepts hexadecimal values. The best example is android:background, android:drawable.  

Here’s an example of a color.xml file. Always define with a meaningful, readable and understandable naming. You can also have a comment line explaining for what purpose the color is defined. 

ColorXML

Layout Definitions

There’s a dedicated folder named ‘layout’ while holds all the xml files for activity. Generally you should see one xml file for each of your activity. This layout xml file contains the view elements or it’s used for designing the user interface. The recommended practice is to code all your view (UI) things within your activity xml file. Although you can programmatically do everything, first try to see whether you can go with the layout xml file so that you have a clear separation of view from your activity code.

Here are some best practices people generally follow. You can have an activity file name to begin with “activity_” similarly for adapters; you can go with “adapter_”, for fragments you can start the file name to begin with “fragment_” etc.

Now let us see how to deal optimize your application for various screen sizes. When designing android apps targeting devices with various screen sizes and density. The density is measured by DIP (device independent pixel); for a 160dip screen 1 DIP is nothing but one pixel. You should be creating a unique layout xml files for each screen sizes. There exist four screen sizes: small, normal, large, xlarge with four different densities: low (ldpi), medium (mdpi), high (hdpi), extra high (xhdpi).

If you have layout files for various screen sizes, the system automatically loads the respective layout from the layout folder while your app is running. Also you don’t have to worry about adjusting the view elements to fit or resize for various device screen sizes.

The below picture shows the layout files for one each for default layout (portrait), landscape and large portrait.

LayoutScreen

Reusing layout files

When it comes to reusing the layout xml, it’s a good practice to have a separate and dedicated layout files which you wish to use in more than one layout. With android, using <include> tag, you can easily import the layout xml file to the layout file which you wish to have. Here’s a good example. Say you have a tab control in your main layout and each, you could separate the each tab out of its own layout file so you will not only have a better control in managing the layout files but you could also reuse the same in multiple layout files. 


Bitmaps

It’s a recommended practice to always provide bitmaps (which must be scaled accordingly) for various densities which are: low (ldpi), medium (mdpi), high (hdpi), extra high (xhdpi). The android system will automatically make use of the bitmaps that you placed for each density. This will make your application to show a high quality, scaled bitmaps when your application gets rendered on various densities. 

While generating bitmaps, it’s always good to go with vector images and scale them accordingly as per the below scale values.

ldpi: 0.75
mdpi: 1.0 (baseline)
hdpi: 1.5
xhdpi: 2.0

The below picture shows the drawable-* folders were you can place your bitmaps for all screen densities.  

Bitmaps

Note – Google prefers the bitmap images to be in PNG format. However *.jpeg is also acceptable.

User Interface Strings

It’s a recommended practice to extract the strings that are being used within the layout xml file into string.xml files. Android provides an easy to maintain string resources within the res -> values folder. 

If you are following this approach in defining all your UI strings in string.xml, you can easily support localization that is; based upon the language settings you can make your app to show the text. Below picture shows the string resources with default “English”. Also it shows how you can define strings for various other languages such as Spanish, French etc.

StringXML

Animations

With android there are several different ways that one can create animations and here are some recommendations. 

If you are targeting your application to devices with pre-Android 3.0 API’s, go with view animation. These are the original animations available in almost all versions of android. However it comes with few limitations, you can only perform simple animations and is applicable for view objects alone. Note – These animations are defined in '/Resources/anim' folder. 

There’s something called property animation which was introduced in Android 3.0 using which is more flexible and extensible too as you can animation is not just limited to view objects. 

The res/ directory and how to use its various subdirectories

The ‘res’ directory is the root folder for resources and it holds all other dedicated folders for managing the resources for your application. 

Let us have a look into how to use each of the sub folders within the ‘res’ directory. Note – In this section we will be only focusing in understanding all the resources, how to define them etc. Later on we will be seeing how to access the same within your layout xml and activity class file. 

Color folder

The 'color' folder under the ‘res’ folder is used to define the color state list resources. You can have one or more xml files for color state list resources and apply the same for your view element. These are special color files with consideration of view states. Say if you consider a button, there are two states – one is pressed and un-pressed. You can provide colors based on the state and which will be applied for a view element based on its state. 

Here’s the syntax for defining the color state list resource xml file. You can one or more items. Please note – the color attribute is the only required attribute and all others are optional you can use it depending upon your requirement.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:color="hex_color"
        android:state_pressed=["true" | "false"]
        android:state_focused=["true" | "false"]
        android:state_selected=["true" | "false"]
        android:state_checkable=["true" | "false"]
        android:state_checked=["true" | "false"]
        android:state_enabled=["true" | "false"]
       
       android:state_window_focused=["true" | "false"] />
</selector> 

Here’s an example of a color state list resource.  Let us define a color for the button pressed and focused.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"
          android:color="#f90"/> 
    <item android:state_focused="true"
          android:color="#ff0000ff"/> 
</selector>

Color-Folder

Values folder

The values folder within the resource directory consists of multiple files such as colors, styles, strings, dimes etc. xml files.

Color.xml

The color.xml is a resource file within the ‘value’ folder and is used to define the colors that you want your application to make use. You can use it to manage all the colors that your application is using; also the values folder can contain files for color state list resources too. We will see in detail about all these things.

Here’s the syntax for defining a simple color xml. It’s an XML file with ‘resources’ as a root node and you can have one or more ‘color’ child nodes with each node having a name attribute indicates the color name. The hex_color represents a color value. 

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="color_name">hex_color</color>
</resources>

Here’s an example of a simple color xml. You can access the color resources from within the layout xml file or within your activity class file. 

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="white">#ffffffff</color>
    <color name="black">#ff000000</color>
    <!-- Date picker widget color -->
    <drawable name="selected_day_background">#ff0092f4</drawable>
</resources>

String.xml

The string.xml is a resource file which holds a string element with a name and a value. Optionally you could also have styling and string formatting. Note – XML strings can be defined for holding a single valued, quantity strings which are also known as plurals or array of strings.   

Here’s an example of a simple string.xml file. You can see below, we have defined a string item with a unique name and you can have a single value per string item.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">HelloWorld</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
</resources>

Here’s an example of a string array defines a collection of days name. You can use this one to display using suitable view elements like spinners. 

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="days_array">
        <item>Monday</item>
        <item>Tuesday</item>
        <item>Wednesday</item>
        <item>Thursday</item>
        <item>Friday</item>
        <item>Saturday</item>
        <item>Sunday</item>
    </string-array>
</resources>

Here’s the usage of string array resource within the layout xml file. Below you can see the emulator output.

<Spinner    
     android:layout_height="wrap_content"
     android:layout_width="match_parent"
     android:id="@+id/daysSpinner"
     android:entries="@array/days_array ">
</Spinner>

Spinner

Quantity strings or Plurals 

The plurals are XML based resources which are mainly used to handle quantity based string resources. Within the plural xml you can define an item for “zero”, “one”, “two”, “many”, “few”, “many”, “other” so that within your activity code, you can select one based on the specified quantity. You can also apply some string formatting for cases like ‘other’ quantity. Note – You should be very careful with the plurals as it might make sense in one language but not in others. Each language has its own grammatical agreement with the quantity. 

Android provides a very helpful method named getQuantityString() using which one can easily get the string resource based on the specified quantity and you don’t really have to worry about which one to select by language. 

Here’s an example of a plural resource were we are defining the plurals for number of articles. 

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <plurals name="numberOfAvailableArticles">
        <item quantity="zero">No article found. </item>
        <item quantity="one">One article found.</item>
        <item quantity="other">%d number of articles found.</item>
    </plurals>
</resources> 

Styles.xml

Style is a resource which can be used for defining the look and feel. Styles can be applied to activity, application level or to a specific view element. 

Here’s an example of a simple style.xml. Here we are defining a text style with a text size set to 10sp, color as RED and text in all CAPS.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="TextStyle" parent="@style/Text">
        <item name="android:textSize">10sp</item>
        <item name="android:textColor">@color/red</item>
        <item name="android:textAllCaps">true</item>
   </style>
</resources> 

There’s a style element property named ‘parent’ which you can use to inherit styles properties. Let us walk through with an example to understand how to inherit style properties for a pre-existing android style. 

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="CustomTabPageIndicator" parent="@style/Widget.TabPageIndicator">
        <item name="android:background">@drawable/tab_indicator_ab_whitehouse</item>
        <item name="android:textSize">20sp</item>
        <item name="android:textColor">@color/red</item>
        <item name="android:paddingLeft">20dip</item>
        <item name="android:paddingRight">20dip</item>
        <item name="android:paddingTop">10dp</item>
        <item name="android:paddingBottom">10dp</item>
    </style>
    <style name="CustomPopupMenu" parent="@android:style/Widget.Holo.Light.ListPopupWindow">
        <item name="android:popupBackground">@drawable/panel</item>
    </style>
</resources> 

Here’s the skeleton of the style.xml for customizing the application theme. The below theme is from a real world application Whitehouse android app. We inherit all the properties from ActionBarSherlock and override the style. 

Please refer this link for more understanding about the ActionBarSherlock - http://actionbarsherlock.com/usage.html

<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.WhiteHouse" parent="@style/Theme.Sherlock.Light.DarkActionBar">
        <item name="popupMenuStyle">@style/WhiteHouse_PopupMenu</item>
        <item name="actionBarItemBackground">@drawable/selectable_background_whitehouse</item>
        <item name="dropDownListViewStyle">@style/WhiteHouse_DropDownListView</item>
        <item name="actionBarTabStyle">@style/WhiteHouse_ActionBarTabStyle</item>
        <item name="actionDropDownStyle">@style/WhiteHouse_DropDownNav</item>
        <item name="actionBarStyle">@style/WhiteHouse_Solid_ActionBar</item>
        <item name="vpiTabPageIndicatorStyle">@style/WhiteHouse_TabPageIndicator</item>

        <item name="android:selectableItemBackground">@drawable/selectable_background_whitehouse
        </item>
        <item name="android:popupMenuStyle">@style/WhiteHouse_PopupMenu</item>
        <item name="android:actionBarItemBackground">@drawable/selectable_background_whitehouse
        </item>
        <item name="android:dropDownListViewStyle">@style/WhiteHouse_DropDownListView</item>
        <item name="android:listViewStyle">@style/WhiteHouse_DropDownListView</item>
        <item name="android:actionBarTabStyle">@style/WhiteHouse_ActionBarTabStyle</item>
        <item name="android:actionDropDownStyle">@style/WhiteHouse_DropDownNav</item>
        <item name="android:actionBarStyle">@style/WhiteHouse_Solid_ActionBar</item>
        <item name="android:panelBackground">@drawable/menu_hardkey_panel_whitehouse</item>
    </style>

    <style name="Theme.WhiteHouse.Dark" parent="@style/Theme.Sherlock">
        <item name="popupMenuStyle">@style/WhiteHouse_PopupMenu</item>
        <item name="actionBarItemBackground">@drawable/selectable_background_whitehouse</item>
        <item name="dropDownListViewStyle">@style/WhiteHouse_DropDownListView</item>
        <item name="actionBarTabStyle">@style/WhiteHouse_ActionBarTabStyle</item>
        <item name="actionDropDownStyle">@style/WhiteHouse_DropDownNav</item>
        <item name="actionBarStyle">@style/WhiteHouse_Solid_ActionBar</item>
        <item name="vpiTabPageIndicatorStyle">@style/WhiteHouse_TabPageIndicator</item>

        <item name="android:selectableItemBackground">@drawable/selectable_background_whitehouse
        </item>
        <item name="android:popupMenuStyle">@style/WhiteHouse_PopupMenu</item>
        <item name="android:actionBarItemBackground">@drawable/selectable_background_whitehouse
        </item>
        <item name="android:dropDownListViewStyle">@style/WhiteHouse_DropDownListView</item>
        <item name="android:listViewStyle">@style/WhiteHouse_DropDownListView</item>
        <item name="android:actionBarTabStyle">@style/WhiteHouse_ActionBarTabStyle</item>
        <item name="android:actionDropDownStyle">@style/WhiteHouse_DropDownNav</item>
        <item name="android:actionBarStyle">@style/WhiteHouse_Solid_ActionBar</item>
        <item name="android:panelBackground">@drawable/menu_hardkey_panel_whitehouse</item>
    </style> 
</resources> 

Here’s how you can set the application theme within the ActionManifest.xml file under <application> element.

<application android:name=".ui.WhiteHouseApplication"
        android:icon="@drawable/ic_launcher"
        android:theme="@style/Theme.WhiteHouse"
        android:label="@string/app_name"> 
&hellip;.
</application>

Dimes.xml

Dimes.xml is used for defining various dimensions for the view elements, activity etc. The dimension is always defined with a unit of measure. The following are the supported dimensions.

By defining the dimensions within the dimes.xml and using the same within the application will benefit in our application running on various screen densities.   

dp – The ‘dp’ is a density independent pixels, a unit which is used to either scale up or down based on the density of the screen. Android application generally run on various devices with a different screen density; in such cases one should be developing an application were the view elements can be scaled up or down by the densities. These units are relative to 160 dots per inch screen; were 1 dip is considered as 1pixel. A screen with a higher density, the number of pixel per inch will be scaled up and the ratio of pixels to dip is purely dependent on the screen density. 

sp – It’s scale independent pixel which is much similar to dp unit. When used, it will scale up or down based on the user font preferences. Whenever you are specifying the font sizes say for example you have a Textview or EditText element, the recommended practice is to go with a ‘sp’ unit as the element gets scaled accordingly based on the screen density and user font preference. 

pt – The ‘pt’ unit is 1/72 of an inch based on the physical size of the screen.

px – The ‘px’ unit is points per scale, the actual number of pixels on the screen. Note – It’s not a recommended unit because whatever the actual representation that you are defining varies by devices with screen densities. The number of pixels per inch varies by density and that’s being said, a higher resolution screen has more pixels per inch the actual representation cannot be really used in such cases. 

mm – The ‘mm’ unit is the millimeters and is based on the physical screen size.

in – The ‘in’ unit is the inches, and it’s also based on the physical screen size. 

Here’s an example of a dimes.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="TextviewHeight">25dp</dimen>
    <dimen name="TextviewWidth">150dp</dimen>
    <dimen name="FontSize">20sp</dimen>
</resources> 

Here’s how you can use the above dimension. For demonstration purpose, we will use a simple example of setting the layout height, width and text size of a TextView element. 

<TextView
    android:layout_height="@dimen/TextviewHeight"
    android:layout_width="@dimen/TextviewWidth"
    android:textSize="@dimen/FontSize"/>

Layout folder

The layout folder within the resource ‘res’ directory, holds all the layout xml files for each activity within your application. The layout files define the user interface for the activity. Whenever you are creating a new activity, you will see this layout xml file being created. There’s a reason why we have that file, it is used to separate the activity UI from the underlying activity logic. 

Here’ an example of our Helloworld android sample layout xml file.  Also notice the usage of dimes.xml and string resource for displaying ‘Hello world’ text. 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".FirstActivity">

    <TextView
        android:text="@string/hello_world"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout> 

You could also have a common layout xml files say if you think it can be reused within the application. In such cases you can use <include> or <merge> tags and use existing layouts within the activity layout xml file. Please refer the best practices section of this article for organizing the layout xml files. 

Drawable folder

The drawable folder contains bitmaps, xml files that you can use within your application. Take an example of our Helloworld android application, when you navigate to the resource ‘res’ folder, you will see the below list of directories. Notice all the drawable folders that you can use for various screen sizes and density. Your application should typically have bitmaps for different resolutions in the -mdpi, -hdpi, -xhdpi, -xxhdpi subfolders of res/drawable so that the appropriate bitmaps gets loaded based upon the screen resolution. 

Note – Android considers *.png as a preferred bitmap. Although *.jpeg is considered as acceptable, however *.gif images are discouraged. 

DrawableFolders

Apart from the bitmaps, the drawable folders can also have XML files which are used to describe shapes (color, border, and gradient), state, transitions etc. 

Here’s a technique which you can use to generate images for all screen resolutions by using a 9 path generator tool - http://romannurik.github.io/AndroidAssetStudio/nine-patches.html

All you need to do is select an image from your local harddrive, then select the source density and key in the drawable name as required. Finally the tool lets you download the images for all screen resolutions. 

9patchGenerator

Now let us see the xml files within the drawable folders. 

XML bitmap

An xml bitmap is a resource file within the drawable folder which points to a bitmap file. Here’s the syntax of a XML bitmap file.

<?xml version="1.0" encoding="utf-8"?>
<bitmap
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@[package:]drawable/drawable_resource"
    android:antialias=["true" | "false"]
    android:dither=["true" | "false"]
    android:filter=["true" | "false"]
    android:gravity=["top" | "bottom" | "left" | "right" | "center_vertical" |
                      "fill_vertical" | "center_horizontal" | "fill_horizontal" |
                      "center" | "fill" | "clip_vertical" | "clip_horizontal"]
    android:mipMap=["true" | "false"]
    android:tileMode=["disabled" | "clamp" | "repeat" | "mirror"] />

Note – The source (src) attribute is the required attribute. All other attributes are optional. Here’s an example of a simple bitmap xml file.

<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/blue"
    android:gravity=&rdquo;fill_vertical&rdquo;
    android:antialias=&rdquo;true&rdquo;
    android:tileMode="repeat" />

The filter attribute is set when you wish to make your bitmap contracted or stretched to smooth its appearance.

Nine patch file

A NinePatch is a *png file which you can use it to rendering a stretchable images based on the view. It’s usually used in setting the background of a view, say when you are using a nine patch image to set the activity background, it automatically gets stretched based on the screen density. A Nine path file is defined with the file name as filename.9.png within the drawable resource. Here’s an example of the usage of the nine patch image file to set the background of a button. Assuming you created a nine path image with a file name as 9patch.9.png in this case.

<Button
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:background="@drawable/9patch" />

Note – You can easily create a nine patch image by using the above online nine patch generator tool) or if you navigate to android-sdk\tools folder, you will see a batch file named “draw9patch.bat” when you run, it will open up a tool which you can use to open an existing image and create a nine path image based on it.

Shape drawables

A shape drawables are basically XML files which defines a geometric objects with color, gradients, strokes etc. You can then assign these shape drawables to view elements. For example, you can define a shape drawable something like below and then apply the same to background property for a button widget or within the activity layout ex: Linear or RelativeLayout or any layout for that matter.

<?xml version="1.0" encoding="UTF-8"?>
<shape
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:shape="rectangle">
  <stroke
    android:width="2dp"
    android:color="#F90" />
  <gradient
    android:endColor="#73b1e7"
    android:startColor="#FFE761AD"
    android:angle="60" />
  <corners
    android:topLeftRadius="2dp"
    android:topRightRadius="2dp"
    android:bottomRightRadius="2dp"
    android:bottomLeftRadius="2dp"/>
</shape>  

State drawables

The state drawables are resources that gets applied based on the view elements state. These drawable xml files let us define drawables that can be applied upon the state change of a view element. 
Here’s the syntax for defining the state drawable xml file. The selector element with android is required and also the drawable attribute within the item element is also a required. All other attributes of an item element are optional.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
    android:constantSize=["true" | "false"]
    android:dither=["true" | "false"]
    android:variablePadding=["true" | "false"] >
    <item
        android:drawable="@[package:]drawable/drawable_resource"
        android:state_pressed=["true" | "false"]
        android:state_focused=["true" | "false"]
        android:state_hovered=["true" | "false"]
        android:state_selected=["true" | "false"]
        android:state_checkable=["true" | "false"]
        android:state_checked=["true" | "false"]
        android:state_enabled=["true" | "false"]
        android:state_activated=["true" | "false"]
        android:state_window_focused=["true" | "false"] />
</selector>

Below is an example of a simple state drawable xml file. You can notice below, we have defined all the drawables that needs to be applied based on the view elements state for pressed, focused and the default normal without any state.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"
          android:drawable="@drawable/pressed" /> 
    <item android:state_focused="true"
          android:drawable="@drawable/focused" />    
    <item android:drawable="@drawable/normal" />
 </selector>

Layer List

The layer list is an xml file (saved as layers.xml under drawable folder) which contains a collection of one or more drawable items. When you are using a layer list in view elements, the drawables gets rendered in a way it’s defined within the layer list. Which means the last drawable is shows at the top. You can use this one to display a series or collection of drawables for example; you can render all the bitmaps say in an ImageView element. 
Here’s the syntax of a layer list. Please note the <layer-list> element with the namespace (android) is required one. Also an item element should always consist of a drawable resource set. You can either use a bitmap or set the drawable attribute of an item element.

<?xml version="1.0" encoding="utf-8"?>
<layer-list
    xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:drawable="@[package:]drawable/drawable_resource"
        android:id="@[+][package:]id/resource_name"
        android:top="dimension"
        android:right="dimension"
        android:bottom="dimension"
        android:left="dimension" />
</layer-list>

Here’s an example for a layer list consists of two item elements with a bitmap resource. 

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
      <bitmap android:src="@drawable/one"
        android:gravity="center" />
    </item>
    <item>
      <bitmap android:src="@drawable/two"
        android:gravity="center" />
    </item>
</layer-list>

Transition Drawables

The transition drawables are xml files which defines the drawable resource items. You can use these drawables and make some transition effects. 

Here’s the syntax of a transition drawable xml file. You can have any number of item elements. 

<?xml version="1.0" encoding="utf-8"?>
<transition
xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:drawable="@[package:]drawable/drawable_resource"
        android:id="@[+][package:]id/resource_name"
        android:top="dimension"
        android:right="dimension"
        android:bottom="dimension"
        android:left="dimension" />
</transition>

Here’s an example of a simple transition xml file with two bitmap based drawable items. 

<?xml version="1.0" encoding="utf-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
<item>
      <bitmap android:src="@drawable/one"/>
    </item>
    <item>
      <bitmap android:src="@drawable/two"/>
    </item>
</transition> 

Here’s how you can use transition drawable. The below example demonstrates with a ImageButton view element with a ‘src’ attribute set with a transition drawable. Please note – the button_transition is the transition xml file name under drawable folder.

<ImageButton
    android:id="@+id/button"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:src="@drawable/button_transition" />

Within out activity code file, we will be getting a reference to our ImageButton and then get the TransitionDrawable so that we can make a call to startTransition with an interval to make a transition of first drawable to second based upon the specified time interval. 

ImageButton button = (ImageButton) findViewById(R.id.button);
TransitionDrawable drawable = (TransitionDrawable) button.getDrawable();
drawable.startTransition(200);

Xml folder

The 'xml' folder within a resource ‘res’ directory can contain one or more arbitrary xml files that your application can make use off. 

Here’s an example of an xml resource file. We will be naming it as general_preference.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
                  android:title="@string/prefheader_title_general">
    <CheckBoxPreference
            android:key="@string/pref_key_general_notifications"
            android:title="@string/pref_title_general_notifications"
            android:summaryOn="@string/summary_general_notifications_on"
            android:summaryOff="@string/summary_general_notifications_off"
            android:defaultValue="@bool/default_general_notifications"/>
</PreferenceScreen>

You can read the xml files within your activity file and do something with it. The below class extends itself from PreferenceFragment and loads the general_preference.xml by making a call to addPreferencesFromResource which is a method of PreferenceFragment class.

public class GeneralPreferenceFragment extends PreferenceFragment {
   @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); 

       // Load the preferences from an XML resource
        addPreferencesFromResource(R.xml.general_preference);
     }
} 

Menu folder

Menu folder contains xml file which is used to define the application menus like context, option menu etc.  

Here’s the syntax of a menu xml file.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@[+][package:]id/resource_name"
          android:title="string"
          android:titleCondensed="string"
          android:icon="@[package:]drawable/drawable_resource_name"
          android:onClick="method name"
          android:showAsAction=["ifRoom" | "never" | "withText" | "always" | "collapseActionView"]
          android:actionLayout="@[package:]layout/layout_resource_name"
          android:actionViewClass="class name"
          android:actionProviderClass="class name"
          android:alphabeticShortcut="string"
          android:numericShortcut="string"
          android:checkable=["true" | "false"]
          android:visible=["true" | "false"]
          android:enabled=["true" | "false"]
          android:menuCategory=["container" | "system" | "secondary" | "alternative"]
          android:orderInCategory="integer" />
    <group android:id="@[+][package:]id/resource name"
           android:checkableBehavior=["none" | "all" | "single"]
           android:visible=["true" | "false"]
           android:enabled=["true" | "false"]
           android:menuCategory=["container" | "system" | "secondary" | "alternative"]
           android:orderInCategory="integer" >
        <item />
    </group>
    <item >
        <menu>
          <item />
        </menu>
    </item>
</menu>

Here’s an example of a simple menu xml file. The menu element with the android namespace is a required one. You can notice below, some of the menu items are defined with an icon. You can also set the visibility of the menu to ‘true’ or ‘false’.

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".ResourceActivity" >
    <item  android:id="@+id/itemHome"
        android:title="Home"/>

    <item  android:id="@+id/itemArticles"
        android:title="Articles"/>

    <item  android:id="@+id/itemQuestionAnswers"
        android:title="Question Answers"/>

    <item  android:id="@+id/itemDiscussions"
        android:title="Discussions"/>
</menu>

Here’s the code snippet of activity class file to inflate the menu xml file.

@Override  
public boolean onCreateOptionsMenu(Menu menu) {  
        getMenuInflater().inflate(R.menu.main, menu);//Menu Resource, Menu  
        return true;  
}

Here’s how the menu look like in design mode. 

Menu

Raw folder

The raw files within the ‘raw’ directory consist of arbitrary raw files. Android automatically generates an id for each of the resources; in our case the raw files will also have a unique resource id. You can access all raw files using ‘R’ class. If the application wants to use some music files, it’s a good place to store those music files in raw folder so that you can access the same and play them whenever you need it.

Here’s an example of a simple raw file. The file contains day names.

<days>
  <day value="monday" />
  <day value="tuesday" />
  <day value="wednesday" />
  <day value="thursday" />
  <day value="friday" />
  <day value="saturday" />
  <day value="sunday" />
</days>

Here’s the code snippet to read the raw file. We are using DocumentBuilder and Document classes to read all the day nodes within the root node ‘days’.

try 
{
      ArrayList<String> items=new ArrayList<String>();
      InputStream in=getResources().openRawResource(R.raw.days);
      DocumentBuilder docBuilder=DocumentBuilderFactory
                                .newInstance()
                                .newDocumentBuilder();

      Document document = docBuilder.parse(in, null);
      NodeList days = document.getElementsByTagName("day");
      
      for (int i=0;i<days.getLength();i++) {
        items.add(((Element)days.item(i)).getAttribute("value"));
      }   
   
      in.close();
}
catch (Throwable t) {         
          e.printStackTrace();
}


Anim folder

The ‘anim’ folder is specially used for animation. One can either go with property or view animation.  There are two flavors of view animation, the tween animation and frame animation. Here we will be discussing how to define these animations. Later on, we will see how it works with a sample animation.
 
Property Animation

It’s the animation XML file defined within the ‘res/anim’ sub directory, which is used to modify the properties of the target object. You can modify the view elements background color, alpha value etc. for the amount of time that you are set within the xml.

Here’s the syntax for defining the property animation. It’s using objectAnimator and animator. You need to specify the property name for the objectAnimator that specifies for which property of a view object you wish to create animation. 

If you wish to infinitely repeat the animation, set the repeatCount property to -1.

<set android:ordering=["together" | "sequentially"]>
    <objectAnimator
        android:propertyName="string"
        android:duration="int"
        android:valueFrom="float | int | color"
        android:valueTo="float | int | color"
        android:startOffset="int"
        android:repeatCount="int"
        android:repeatMode=["repeat" | "reverse"]
        android:valueType=["intType" | "floatType"]/>
    <animator
        android:duration="int"
        android:valueFrom="float | int | color"
        android:valueTo="float | int | color"
        android:startOffset="int"
        android:repeatCount="int"
        android:repeatMode=["repeat" | "reverse"]
        android:valueType=["intType" | "floatType"]/>
    <set>
        ...
    </set>
</set>

View Animation

The Tween animation is used to create animations (such as scaling, translation, rotating, fading etc.) by performing a series of transformations on a single image. 

Here’s the syntax for defining the view animation. You can apply the view animation to any view element as opposed to property animation which is applicable to the specified properties only.

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@[package:]anim/interpolator_resource"
    android:shareInterpolator=["true" | "false"] >
    <alpha
        android:fromAlpha="float"
        android:toAlpha="float" />
    <scale
        android:fromXScale="float"
        android:toXScale="float"
        android:fromYScale="float"
        android:toYScale="float"
        android:pivotX="float"
        android:pivotY="float" />
    <translate
        android:fromXDelta="float"
        android:toXDelta="float"
        android:fromYDelta="float"
        android:toYDelta="float" />
    <rotate
        android:fromDegrees="float"
        android:toDegrees="float"
        android:pivotX="float"
        android:pivotY="float" />
    <set>
        ...
    </set>
</set> 

Here’s an example to create a fade-in and fade-out animation with duration set to 1000 millisecond. We are altering the alpha property of the view element from 0.1 to 1.0 with the specified duration to create a fade-in effect. To create the fade-out effect, we will just reverse the alpha from and to.

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
  android:interpolator="@android:anim/linear_interpolator">
  <alpha
      android:fromAlpha="0.1"
      android:toAlpha="1.0"
      android:duration="1000"/>
</set>

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
  android:interpolator="@android:anim/linear_interpolator">
  <alpha
      android:fromAlpha="1.0"
      android:toAlpha="0.1"
      android:duration="1000"/>
</set>

The Frame animation is used to create an animation by showing a sequence of images. When used, it shows the animation as if like a movie, frame by frame one after the other in the order as we define in frame animation xml file. 

Here’s the syntax of frame animation. If you wish to loop animation, set the oneshot attribute of animation-list to ‘false’. You could have one or more item element which is used to animate the drawable resource for the specified duration. 

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot=["true" | "false"] >
    <item
        android:drawable="@[package:]drawable/drawable_resource_name"
        android:duration="integer" />
</animation-list>

Alternative Resources 

In an android application, whenever you are defining resources, you should always provide alternate resources to support various screen configurations. Here’s how android loads the resources, at runtime based on the device screen density and configuration, android loads the respective resources from the resource ‘res’ folder. 

The alternate resources are organized within the main ‘res’ directory just like other resource sub folders. Alternate resource folder should always be named with <ResourceName>-<Qualifier>. The resource corresponds to the default resource directory name. The qualifier depends on the individual configuration.
Let us take an example of drawable resources. You will notice the below sub directories for hdpi, mdpi, xhdpi and xxhdpi. Depending upon the screen density, android loads the resources from the respective drawable sub directories.

ResourceDirectories

Now let us take a look into understanding the rules that applies when adding qualifiers to a resource type.

1. There may be more than one qualifier, in such cases the qualifier should be separated by a dash. Here’s an example - layout-large-hdpi.

2. Qualifiers must be in the order they appear as shown below. Please check the reference section at the end of this article to know more about the same.

Configuration

Qualifier

Description

MCC and MNC

mcc310

mcc310-mnc004 etc.

The mobile country code, optionally followed by a mobile network code is used as a qualifier. When you are using a phone, the above codes are obtained based from the GSM SIM card. 

Here’s an example - mcc310 is U.S. on any carrier, mcc310-mnc004 is U.S. on Verizon

Please refer the below link to get the complete list of codes - http://mcclist.com/

Language and region

en

en-rUS
etc.

The two letters ISO 639-1 with the optional 2 letter region code based on ISO-3166-alpha-2.

Note – If you wish to provide both qualifiers then you must separate them with –r.
 

To target english speaking locales, you can use en and to be specific if you want to go with region, use en-rUS.

Layout direction

ldrtl
ldltr

The layout direction of your application which is either right to left or left to right. Also applicable to drawables, or values too.

If you wish to provide support say for Chinese language, then you should be ideally having a default layout and layout specific to Chinese language, then you must be having a layout folder as layout-zh.

Note – Left to right is by default but if you wish to support right to left then you should be having a layout folder - layout-ldrtl with the layout xml file.
 

To enable right-to-left layout feature, you must set supportsRtl to "true" and set targetSdkVersion to 17 or higher. You can do these things in AndroidManifiest.xml, application element.

smallestWidth

sw320dp

sw600dp
etc.

As the name itself indicates, it’s the smallest possible width of the screen that you wish to support. You can use this qualifier to always ensure that regardless of the screen orientation, the device always has the specific screen size.


Here are the common screen sizes.


320, for devices with screen configurations such as:

240x320 ldpi (QVGA handset)

320x480 mdpi (handset)

480x800 hdpi (high density handset)

480, for screens such as 480x800 mdpi (tablet/handset).

600, for screens such as 600x1024 mdpi (7" tablet).

720, for screens such as 720x1280 mdpi (10" tablet).

Note – It’s available in API level 13 (Android 3.2) and above.

Available Width

w720dp
w1024dp

etc.

Specifies the available width in dp unit for which the resources should be used. Pease note, It varies by screen orientation landscape vs portrait. The available width gets changed accordingly. It’s added in API level 13.

Available Height

h720dp
h1024dp

Specifies available height in dp unit for which the resources should be used. Pease note, It varies by screen orientation landscape vs portrait. The available height gets changed accordingly. It’s added in API level 13.

Screen size

small
normal
large
xlarge

You could also specify the resources to load based on the screen size.

Small screen – The minimum layout size of approximately 320x426 dp. Ex - QVGA low density and VGA high density.


normal screen – The minimum layout size of approximately 320x470 dpi. Ex - WQVGA low density, HVGA medium density, WVGA high density.

large – The minimum layout size of approximately 480x640 dip. Ex - VGA and WVGA.


xlarge – The screens that are considerably larger than medium-density HVGA screen are considered as xlarge one. The minimum layout size of approximately 720x960 dips.

Screen aspect

long

notlong

long: Long screens, such as WQVGA, WVGA, FWVGA

notlong: Not long screens, such as QVGA, HVGA, and VGA

Screen orientation

port
land

The portrait and landscape orientation. This can change anything during the lifetime of the application. The appropriate alternate resources gets loaded based on the orientation.

User Interface mode

car
desk
television
appliancewatch

car: When the device is displaying in a car dock.

desk: When the device is displaying in a desk dock.

television: When the device is displaying on a television.

appliance: When the device is serving as an appliance, with no display

watch: When the device has a display and is worn on the wrist.

Night mode

night
notnight

night: Night time.

notnight: Day time.

Screen pixel density (dpi)

ldpi

mdpi

hdpi

xhdpi

nodpi

tvdpi

The alternate resources also gets loaded based on the screen pixel density.

ldpi – low density with a pixel density of 120dpi.
mdpi – medium density with a pixel density of 160dpi.
hdpi – high density with a pixel density of 240 dpi.

xhdpi – extra high density with a pixel density of 320 dpi.

xhdpi – extra extra high density with a pixel density of 480 dpi.

nodpi – if you don’t want the bitmap resources to be scaled to match the device density you can use this one.

tvdpi – It was introduced in API level 13. These are screens with the density between mdpi and hdpi with a pixel density of approximately 213dpi.

Touchscreen type           

 

notouch
finger

notouch: The device does not have a touchscreen.

finger: The device has a touchscreen. The interaction happens when the user touches the screen with his fingers.

Keyboard availability     

 

keysexposed

keyshidden

keyssoft

It specifies what type of keyboard available.

keyssoft – specifies the device has a softkey enabled.

keyshidden – specifies that soft keys are not enabled but the device has a hardware keyboard but it’s hidden.

Primary text input method

nokeys

qwerty

12key

nokeys: The device has no hardware keys for text input.

qwerty: The device has a hardware qwerty keyboard. It may or may not be visible to user.

12key: The device has a hardware 12-key keyboard. It may or may not be visible to user.

Navigation key availability           

 

navexposed

navhidden

navexposed: The navigation keys are available to the user.

navhidden: The navigation keys are not available (such as behind a closed lid).

Primary non-touch navigation method               

 

nonav

dpad

trackball

wheel

Specifies the possible non-touch navigations.

nonav – The device has no navigation facility other than the touch screen.

dpad – The device has a d-pad (directional-pad) is available for navigation.

trackball - The device has a trackball for navigation

wheel -  The device has one or more directional wheels available for navigation. Note – This one is not common.

Platform Version (API level)

v3
v4
v7
etc.

Specifies the API level supported by the device.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Accessing Resources

You have come this far by defining all the resources that is required for your application. Now it’s the time to learn how to access the resources. Before we dig inside in accessing the resources, here are few things to understand. 

All the resources that you are using within your application get compiled. There’s one tool named aapt which generates the R class. The R class in android is an auto generated class and you should never modify that one. It contains all the resource Ids for all the resources that you are using within the ‘res’ resource directory. 

Here’s the R class file for our Helloworld app. You can notice below, it has all the sub classes for all the resource types that you have used. For example - drawable, dimen, layout etc. Also there’s a static integer defined for each of the resources that you use within the resource sub directories.

public final class R {
    public static final class attr {
    }
    public static final class dimen {
        public static final int activity_horizontal_margin=0x7f040000;
        public static final int activity_vertical_margin=0x7f040001;
    }
    public static final class drawable {
        public static final int ic_launcher=0x7f020000;
    }
    public static final class id {
        public static final int action_settings=0x7f080000;
    }
    public static final class layout {
        public static final int activity_resource=0x7f030000;
    }
    public static final class menu {
        public static final int resource=0x7f070000;
    }
    public static final class string {
        public static final int action_settings=0x7f050000;
        public static final int app_name=0x7f050001;
        public static final int hello_world=0x7f050002;
    }
    public static final class style {
        /**  Customize your theme here. 
         */
        public static final int AppTheme=0x7f060000;
    }
}

If you are wondering where to find the R class, here it is within the build -> generated -> source -> r sub directory.

RClass

When you are using the resources within the layout xml file or activity class file, you don’t have to ever look into the R class and understand how to use them. The R class is composed of sub classes for each of the resource types. And within each of the sub classes, the resource names are defined as static final integer, the resource names within the R class is defined as same name as file name but excluding extension. 

Now let us try to understand how we can access the resources. There are two ways you can access; either directly within the layout xml or you could also access the same from within the activity class file. Let us create a sample project to try to understand how to access resources both within the layout xml and also inside the activity class file.

Here’s the code snippet to access resources within the layout xml file. There are several things you can see below. 

1.    We are using dimes.xml to set some of the dimensions like padding for the RelativeLayout. 
2.    The background for the RelativeLayout is set based on the drawable resource – blue. This sample project makes use of nine patch generator tool - http://romannurik.github.io/AndroidAssetStudio/nine-patches.html for generating drawables for setting the activity background. 
3.    colors.xml is used to set the button background color.
4.    string.xml is used to set the button text property.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".ResourceActivity"
    android:background="@drawable/blue">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/read_rawfile_text"
        android:id="@+id/btnReadRawFile"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="@dimen/margin_huge"
        android:background="@color/white"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/show_article_title"
        android:id="@+id/btnShowArticle"
        android:layout_marginTop="@dimen/margin_huge"
        android:background="@color/white"
        android:layout_below="@+id/btnReadRawFile"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/dispaly_animation_text"
        android:id="@+id/btnDisplayAnimation"
        android:layout_marginTop="@dimen/margin_huge"
        android:background="@color/white"
        android:layout_below="@+id/btnShowArticle"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

Here’s the code snippet of string.xml within the res/values sub directory.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">ResourcesSample</string>
    <string name="action_settings">Settings</string>
    <string name="read_rawfile_text">Read Raw File</string>
    <string name="show_article_title">Show Article</string>
    <string name="title_activity_show_article">ShowArticleActivity</string>
    <string name="hello_world">Hello world!</string>
    <string name="dispaly_animation_text">Display Animation</string>
    <string name="title_activity_dispaly_animation">DispalyAnimationActivity</string>
</resources>  

Here’s the code snippet for dimes.xml

<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <dimen name="margin_tiny">4dp</dimen>
    <dimen name="margin_small">8dp</dimen>
    <dimen name="margin_medium">16dp</dimen>
    <dimen name="margin_large">32dp</dimen>
    <dimen name="margin_huge">64dp</dimen>
</resources>

Now let us focus on the activity class file coding to access the Buttons and handle the onClick event handler. Here’s the code snippet for the same. Notice how we are accessing the button view element by its resource id. 

@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_resource);

        // Show Read Raw file Activity
        Button btnReadRawFile = (Button)findViewById(R.id.btnReadRawFile);
        btnReadRawFile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getBaseContext(), ReadRawFileActivity.class);
                startActivity(intent);
            }
        });

        // Show Article Activity
        Button btnShowArticle = (Button)findViewById(R.id.btnShowArticle);
        btnShowArticle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getBaseContext(), ShowArticleActivity.class);
                startActivity(intent);
            }
        });

        // Display Animation Activity
        Button btnDisplayAnimation = (Button)findViewById(R.id.btnDisplayAnimation);
        btnDisplayAnimation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getBaseContext(), ShowAnimationActivity.class);
                startActivity(intent);
            }
        });
}

Let us now see how to display a menu. We will be creating a menu resource with a file name articles.xml. 

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".ResourceActivity">
    <item  android:id="@+id/itemHome"
        android:title="Home"/>
    <item  android:id="@+id/itemArticles"
        android:title="Articles"/>
    <item  android:id="@+id/itemQuestionAnswers"
        android:title="Question Answers"/>
    <item  android:id="@+id/itemDiscussions"
        android:title="Discussions"/>
</menu>

Here’s the code snippet to display menu. We need to override the onCreateOptionsMenu within the activity class file and use the R class to access out menu xml.

@Override
 public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.articles, menu);
        return true;
 }

ResourceAccess-Menu

Now let us see how to read a raw file. First we need to create a new folder named ‘raw’ under the resource ‘res’ directory. Here’s the xml that we are reading within out activity class file. Let us name this one as days.xml.

<days>
    <day value="monday" />
    <day value="tuesday" />
    <day value="wednesday" />
    <day value="thursday" />
    <day value="friday" />
    <day value="saturday" />
    <day value="sunday" />
</days> 

Here’s the code snippet to read the raw file and display the same in TextView view element. We need to first get the resource instance by making a call to getResources() and then to read the raw file we are making a call to openRawResource method with the raw file name obtained from the R class. This method returns an InputSteam, and then we will read all text and display the same in TextView.

@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_read_raw_file);

        TextView txtRawTextView = (TextView)findViewById(R.id.txtRawTextView);
        InputStream inputStream = null;
        try {
            inputStream = getResources().openRawResource(R.raw.days);
            byte[] reader = new byte[inputStream.available()];
            while (inputStream.read(reader) != -1) {}
            txtRawTextView.setText(new String(reader));
        } catch(IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
 } 

Here’s the snapshot of the raw file reading activity.

ResourceAccess-ReadRawFile

Let us now focus on how to read plurals. You can create a new resource xml file or you can just use string.xml. Here’s the code snippet were we define our plurals with name as ‘numberOfAvailableArticles’.  Within out activity class file, we will be reading the plurals based on this name through R class.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <plurals name="numberOfAvailableArticles">
        <item quantity="zero">No article found. </item>
        <item quantity="one">One article found.</item>
        <item quantity="other">%d number of articles found.</item>
    </plurals>
</resources>

Here’s the code snippet of activity onCreate override. First we need to get the resources instance so that we can make a call to getQuantityString passing in the plural resource id and count so that we obtain the resource value and display the same in TextView.

@Override
 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_article);

        // Reference the TextView to display the number of articles.
        TextView txtShowArtile = (TextView)findViewById(R.id.txtShowArtile);
        int count = 10; // Let us hardcode this one for demo.
        Resources res = getResources();
        String articlesFound = res.getQuantityString(R.plurals.numberOfAvailableArticles, count, count);
        txtShowArtile.setText(articlesFound);
 }

Here’s the snapshot of our Resource sample activity to get the quantity based on the count and display the same in TextView.

ResourceAccess-Plurals

Now let us play with little animation. We will be creating an animation ‘anim’ resource file and using the same to create a basic animation. Create a new animation resource file under ‘res/anim’ , let us name it as jump.xml. Let us do some scaling and rotation. 

<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:shareInterpolator="false">
    <scale
        android:interpolator="@android:anim/accelerate_decelerate_interpolator"
        android:fromXScale="1.0"
        android:toXScale="1.4"
        android:fromYScale="1.0"
        android:toYScale="0.6"
        android:pivotX="50%"
        android:pivotY="50%"
        android:fillAfter="false"
        android:duration="500" />
    <set
        android:interpolator="@android:anim/accelerate_interpolator"
        android:startOffset="700">
        <scale
            android:fromXScale="1.4"
            android:toXScale="0.0"
            android:fromYScale="0.6"
            android:toYScale="0.0"
            android:pivotX="50%"
            android:pivotY="50%"
            android:duration="400" />
        <rotate
            android:fromDegrees="0"
            android:toDegrees="-45"
            android:toYScale="0.0"
            android:pivotX="50%"
            android:pivotY="50%"
            android:duration="400" />
    </set>
</set>

Here’s the code snippet of animation activity were we are getting a reference to the ImageView and then we load animation by making a call to static method loadAnimation of AnimationUtils class. Notice that we are making use of R class to get the animation resource based on the resource Id.

public class ShowAnimationActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_animation);

        ImageView image = (ImageView) findViewById(R.id.imageButton);
        Animation animate = AnimationUtils.loadAnimation(this, R.anim.jump);
        image.startAnimation(animate);
    }
}

ResourceAccess-ShowAnimation

If you see the above activity, you will notice the gradient background and it’s coming from the shapes.xml under the drawable sub directory. Here’s the code snippet for the same. Note – You don’t really have to name the file as shapes.xml, you can name as you wish but it should be within the drawable sub directory.

<?xml version="1.0" encoding="UTF-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <stroke
        android:width="2dp"
        android:color="#F90" />
    <gradient
        android:endColor="#73b1e7"
        android:startColor="#FFE761AD"
        android:angle="45" />
    <corners
        android:topLeftRadius="2dp"
        android:topRightRadius="2dp"
        android:bottomRightRadius="2dp"
        android:bottomLeftRadius="2dp"/>
</shape>  

Here’s how we are going to make use of the shapes.xml in setting the activity background. 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.example.codeprojectandroid.resourcessample.ShowAnimationActivity"
    android:background="@drawable/shapes">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageButton"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:background="@drawable/football"/>

</RelativeLayout> 

Let us play with styles, navigate to styles.xml file within the res/values sub directory. Use the below code snippet as a style resource. 

<resources>
    <style name="MyTheme" parent="android:Theme.Light">
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowBackground">@color/orange</item>
        <item name="android:shadowColor">#BB000000</item>
        <item name="android:shadowRadius">.75</item>
    </style>
</resources>

In-order to use the above style, for demonstration purpose we are going to apply the above mentioned style as an application theme. Open up the AndroidManifest.xml file and set the android:theme property to use ‘MyTheme’ which is the style name that we had defined in styles.xml. Please note, that this style is applied at application level which means this style will be applied to all the activities of your application unless the activity does not override the background property.

<application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/MyTheme" >
&hellip;..
</application>

Other tips and best practices

1. Always use ‘dp’ or ‘sp’ units as applicable and do not use pixel (px)

2. Follow the guidelines for defining the alternate resources. It’s always recommended to have an alternate resource. 

3. Use proper icon asset naming conventions. Refer this link to know more - http://developer.android.com/design/style/iconography.html

4. Always use vector graphic bitmaps wherever possible. Android recommends using *.png as a preferred resource. However *.jpeg is also acceptable.  

5. Follow the android design guidelines for styles - http://developer.android.com/design/style/index.html

References

Here’s the link through which I got a full understanding about Android Resource types. This article makes use of the xml file syntax from the below link. 

http://developer.android.com/guide/topics/resources

Some of the resource xml files have been re-used and modified based on the white house android app.

https://github.com/WhiteHouse/wh-app-android/blob/master/res/values/styles.xml

The alternative resources, table content is elaborated based on the below links

http://developer.android.com/guide/topics/resources/providing-resources.html

http://developer.xamarin.com/guides/android/application_fundamentals/resources_in_android/part_3_-_alternate_resources/

Points of Interest

While working in this article, I learnt a lot in handling all possible resources that as a developer should be aware off. I was just amazed of the way how these resources are organized which makes perfect sense for andorid application to run on devices with various screen densities. Also handling alternate resource seemed bit tricky at first, but now I got some understanding on how to deal with it. 

History

Version 1.0 - Published initial version of article covering various aspects of Andorid Resources - 08/24/2014.

Version 1.1 - Added table 'th' border color as orange, with the border style for 'td' 1px width - 08/25/2014.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Ranjan.D
Web Developer
United States United States
Profile
 
Around 9 years of professional software development experience in analysis, design, development, testing and implementation of enterprise web applications for healthcare domain with good exposure to object-oriented design, software architectures, design patterns, test-driven development and agile practices.
 
In Brief
 
Analyse and create High Level , Detailed Design documents.
Use UML Modelling and create Use Cases , Class Diagram , Component Model , Deployment Diagram, Sequence Diagram in HLD.
 
Area of Working : Dedicated to Microsoft .NET Technologies
Experience with : C# , J2EE , J2ME, Windows Phone 8, Windows Store App
Proficient in: C# , XML , XHTML, XML, HTML5, Javascript, Jquery, CSS, SQL, LINQ, EF
 
Software Development
 
Database: Microsoft SQL Server, FoxPro
Development Frameworks: Microsoft .NET 1.1, 2.0, 3.5, 4.5
UI: Windows Forms, Windows Presentation Foundation, ASP.NET Web Forms and ASP.NET MVC3, MVC4
Coding: WinForm , Web Development, Windows Phone, WinRT Programming, WCF, WebAPI
 
Healthcare Domain Experience
 
CCD, CCR, QRDA, HIE, HL7 V3, Healthcare Interoperability
 
Others:
 
TTD, BDD
 
Education
 
B.E (Computer Science)
 
CodeProject Contest So Far:
 
1. Windows Azure Developer Contest - HealthReunion - A Windows Azure based healthcare product , link - http://www.codeproject.com/Articles/582535/HealthReunion-A-Windows-Azure-based-healthcare-pro
 
2. DnB Developer Contest - DNB Business Lookup and Analytics , link - http://www.codeproject.com/Articles/618344/DNB-Business-Lookup-and-Analytics
 
3. Intel Ultrabook Contest - Journey from development, code signing to publishing my App to Intel AppUp , link - http://www.codeproject.com/Articles/517482/Journey-from-development-code-signing-to-publishin
 
4. Intel App Innovation Contest 2013 - eHealthCare - http://www.codeproject.com/Articles/635815/eHealthCare
 
5. Grand Prize Winner of CodeProject HTML5 &CSS3 Article Content 2014

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web01 | 2.8.140916.1 | Last Updated 25 Aug 2014
Article Copyright 2014 by Ranjan.D
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid