Android provides us with the ability to use image resources in our applications. We can put image files in res/drawable directory and access them from the xml layout or by the generated ID from class file.

You can use image files of the following formats:
  • PNG
  • JPEG
  • GIF
Notice that there are two restrictions:
  • If you use two files with the same base name you will receive an error. You cannot use two files like Hello.jpeg and Hello.png.
  • If you create any subdirectory under res/drawable directory any image files in it will be ignored.
Now let’s demonstrate how can we use image resources

We will place an image called android.jpeg in res/drawable directory

We can use it from xml layout as this
<imageview android:layout_height="wrap_content" android:layout_width="wrap_content" android:src="@drawable/android" /%gt;

Or from code as this
ImageView img=(ImageView)findViewById(;

or like this to get the image as a drawable object

ImageView img2=(ImageView)findViewById(;
Drawable drawable=this.getResources().getDrawable(;

Color drawable Resources:
You can define XML files that contain definitions for color drawable resources which are color rectangles that can be used as backgrounds

You can define the color drawable resources in values/strings.xml file or by creating a custom xml file to hold these resources

You define color drawable resources like this:
<drawable name="redBox">#f00</drawable>
You can use it from xml layout like this

Or from code like this:
TextView txt=(TextView)findViewById(;

or like this:
ColorDrawable drawable2=(ColorDrawable)this.getResources().getDrawable(R.drawable.redBox);

or this
notice that if the textview does not have text the background color will not appear.

Download a demo application from here