Click here to Skip to main content
15,867,594 members
Articles / Mobile Apps / Android

Beginner’s Guide to Organizing/Accessing Android Resources

Rate me:
Please Sign up or sign in to vote.
4.65/5 (6 votes)
22 Aug 2014CPOL6 min read 14K   16   5
Beginner’s Guide to Organizing/Accessing Android Resources with clear and brief explanation

Introduction

In this article, we will see together different Android Resources, their types, definitions , with examples to describe how to use and access these resources.[Article  #6]

Android Resource Types

1st thing you have to know that all resources are included inside /res folder in your project 

Image 1

By navigation into /res folder, you will find the following folders:

  • drawable-hdpi
  • drawable-ldpi
  • drawable-mdpi
  • drawable-xhdpi
  • layout
  • menu
  • values
  • color ( manually added )

Let's discuss what each of these resources does.

/Res/drawables

1. drawable-hdpi

You can place bitmap/ PNG Images to fit with high resolution screens (640dp X 480dp) 

2. drawable-ldpi

You can place bitmap/ PNG Images to fit with low resolution screens (240dp X 320dp) 

3. drawable-mdpi

You can place bitmap/ PNG Images to fit with medium resolution screens (320dp X 480dp) 

4. drawable-xhdpi

You can place bitmap/ PNG Images to fit with xlarge resolution screens (640dp X 960dp) 

Ok! we understood the difference between these 4 different folders but maybe some questions in mind

Q1 - Must i add the same image with 4 different sizes to fit the 4 drawable folders?

No, you don't have to do so. You can only place 1 or more version o the image and during runtime the application will select the most appropriate version of the resource. Suppose the device is hdpi and you don't have an image in hdpi folder then it will select from mdpi folder or if only 1 version exists of this resource so it will select it for all devices BUT this isn't the right solution since the image will stretch or shrink automatically and you won't have control on it.

Q2 - Do i have to design my icons with different sizes to fit with all screens?

You can do that but there is another solution that is called 9-patch

9-patch Bitmaps

It's 1-pixel transparent border around your bitmap and by drawing a black pixels on the top and left of your bitmap you can define which parts of your image allowed to stretch.

You can implement  9-patch bitmap using this online generator: Online 9-patch Generator

Image 2

1. Select Source Image and Source density

Image 3

Don't Forget to look at Interactive Preview to see the result achieved

Image 4

2. Click Auto Stretch to decide the part of the image that can be stretched then click trim->stretch region then click auto stretch again

Image 5

3. Click trim->stretch region then click auto stretch again

Image 6

4. Do the same for the other bottom left of the bitmap and see the result bitmap

Image 7

5.Dowload .zip files and use them in your project 

Image 8

6.After Extracting the downloaded file, you should find 4 folders with our 4 drawable folders and inside each folder the corresponding 9-patch bitmap

Image 9

7.Include the 4 bitmaps into your project as follow

Image 10

You can access this res/drawable through .XML Layout by using @drawable/bitmap name

//Added ImageView to display our drawable
<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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ImageView 
        android:id="@+id/imgView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/image_code"/> 

</RelativeLayout>

Or through code by using .setImageResource(R.drawable.imagename)

C++
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
        
    ImageView imgView = (ImageView)findViewById(R.id.imgView);
    imgView.setImageResource(R.drawable.image_code);
}

You can do the same previous steps in any image or drawable that you want to add into your project.

/Res/Layout

You use this resource folder to hold all your layout ( that represents the design of your activity) files.

As you saw in previous articles or you can check my article about Design Layout : Design My Android Layout, we create all our layouts that we need inside this folder and access it through code.

 

N.B : You can use the same layout multiple of times with different activites

You can set which layout that activity should use as its default layout through code as follows:

//Inside onCreate function, you can setContentView and access the layout from R.layout.layoutname
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
        
    ImageView imgView = (ImageView)findViewById(R.id.imgView);
    imgView.setImageResource(R.drawable.image_code);
}

/Res/menu

We came to one of the most important resource folder as the previous ones. By navigation into your code that was created automatically, you will see the following code

Image 11

This code display a menu whenever user click on menu button while using this activity, you can acess your menu by R.menu.menuname

As we see in the below code that we have menu called main.xml and it consists of 1 item.

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="@string/action_settings"/>

</menu>

We can add different menu items,simply by adding a new item as follows

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="@string/action_settings"/>
    
    <item
        android:id="@+id/action_help"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="Help"/>

</menu>

I added another menu item called Help and by clicking on menu button of my emulator the menu appears at the bottom

Image 12

Q3 - Does it always appear on the bottom?

No,it depends on the machine your are running the machine at and the API level as well as the theme you are using.

 Q4 - Ok! now i have a menu, how can i acess these items so they do some action on user click?

We can do this action through code only, you need to ovveride a default function exists for this type of action that is called onOptionsItemSelected.

You have to create a switch on menu item id and for each case do some action as in the following code

@Override
public boolean onOptionsItemSelected(MenuItem item) {
  // TODO Auto-generated method stub
  switch (item.getItemId()) {
    //Case Settings Clicked
    case R.id.action_settings:
      Toast toast = Toast.makeText(this.getApplicationContext(), "Settings clicked!", Toast.LENGTH_LONG);
      toast.show();
      return true;

    //Case Help Clicked
    case R.id.action_help:
      Toast toast_Help = Toast.makeText(this.getApplicationContext(), "Help clicked!", Toast.LENGTH_LONG);
      toast_Help.show();
      return true;
       
    default:
      return super.onOptionsItemSelected(item);
  }
}

Image 13

 Q5 - Must i add a menu to my activity?

No, it's optional. If you don't want to display a menu,remove these 2 functions (IF Exists) from your activity onCreateOptionsMenu & onOptionsItemSelected

 

/Res/values

Talking about values folder is talking about its subdirectories :

  1. dimens.xml
  2. strings.xml
  3. styles.xml
  4. colors.xml

1.dimens.xml

You use this xml file to add some dimensions that you want to use many times in your application. As example you can create a dimension for "Margin Top" of all your application layouts.

Benefits : when you need to change the margin top of all your activities, you just change the value once and it applies for all activies instead of navigating in all your activies and change the value and maybe you forget to change one or more values

You can add a new dimen value as follow:

<dimen name="activity_margin_top">20dp</dimen>

and full code would be :

<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="activity_margin_top">20dp</dimen>
</resources>

And you can use the dimen value created into your .XML Layout by @dimen/dimension name

<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:layout_marginTop="@dimen/activity_margin_top"
    tools:context=".MainActivity" >

</RelativeLayout>

 Q6 - What else can i use this .XML with?

You can set all constants parameters that represents dimension like margins, paddings, and font sizes.

2.strings.xml

as it explains itself, we use it to save constants strings like App name or any constants name that we will need alot in our application.

By default you will find these values in the .XML

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">HelloWorld</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="TextViewHint">Enter Your Name!</string>
    <string name="ButtonSubmit">Submit</string>

</resources>

And You can access these values inside your xml layout by @string/string name

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="@string/action_settings"/>

</menu>

3.styles.xml

If you want to create a custom theme for your application then your code will start from this .XML file, i prefer to explain this file from the provided code and check the comments

<resources>
    //Here this your Base Theme that inherets from android:Theme.Light provided by Google
    //You can apply any changes you want to add to all your application
    <style name="AppBaseTheme" parent="android:Theme.Light">
          
    </style>

    //If you want to customize a theme or some specific items for a particular item  simply 
    // inheret from AppBaseTheme
    // and do any customizations inside this new style and make your application get 
    // from this style
    <!-- Application theme. -->
    <style name="AppTheme" parent="AppBaseTheme">
        <!-- All customizations that are NOT specific to a particular API-level can go here. -->
    </style>

</resources>

And you choose your default style from AndroidManifest.xml

1. Open your AndroidManifest.xml

2. Look for this code

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

3. Change android:theme ="@style/style name">

Also an Example for changing the background of all our application, we can set the default background inside our style 

<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
    <!-- All customizations that are NOT specific to a particular API-level can go here. -->
    <item name="android:background">#FF0000</item>
</style>

Image 14

N.B: To access some other values to change rather than background color, just type in name android: and you will find all possible values.

4.colors.xml

You can add another .XML file to hold some default colors that you need.

1.Create a new XML File

Image 15

2.Insert colors as name and choose resources ( your only option)

Image 16

3. Click Finish

4. You can add new item as follow

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="light_green">#c5f16b</color>
</resources>

And you can access your color by @color/color name

<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
    <!-- All customizations that are NOT specific to a particular API-level can go here. -->
    <item name="android:background">@color/light_green</item>
</style>

 Q7 - Do I have to add all colors in order to use them or there is some default colors?

Yes of course, there is some default colors and you can use them by @android:color/pick a color

Conclusion

I hope that i explained with a detailed descriptions of all resources and benefits of each one as well as best practises for each of these resources.

And try your best and do what ever you want and insert some data in wrong place etc.. until you get the best place for everything and never forget to GET YOUR HAND DIRTY IN CODING

License

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


Written By
Software Developer eSpace Software Company
Egypt Egypt
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionMore Resources Types Pin
DaveyM6925-Nov-15 5:00
professionalDaveyM6925-Nov-15 5:00 
AnswerRe: More Resources Types Pin
Ahmed Alaa El-Din8-Dec-15 1:38
Ahmed Alaa El-Din8-Dec-15 1:38 
QuestionGood Article Pin
apembo16-Sep-14 6:50
apembo16-Sep-14 6:50 
AnswerRe: Good Article Pin
Ahmed Alaa El-Din16-Sep-14 7:23
Ahmed Alaa El-Din16-Sep-14 7:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.