Tutorial details

Android Drawables - Tutorial | App Code for Sale | Preview

Android Drawables - Tutorial | Android Tutorial

How to use Drawables in Android

Overview PAGE TOP

This tutorial describes the usage of Drawables in Android.

1. Drawables PAGE TOP

A Drawable resource is a general concept for a graphic which can be drawn. The simplest case is a graphical file, which would be represented in Android via a BitmapDrawable class. Bitmaps are typically stored in one of the res/drawable folders. The Android project creation wizard creates several of these folders by default, you can provide different sized files for different resolutions of Android devices. If you only provide one file for all sizes the Android system will scale the resource.

In addition to graphical files, Android supports XML drawables and 9-patch graphics. XML drawables are used to describe shapes (color, border, gradient), State and Transitions and more.

9-patch graphics are used to define which part of a graphic should be stretched if the View which uses this graphic is larger than the graphic.

2. Accessing drawables PAGE TOP

Graphical assets which are stored in the folders starting with drawable are managed by the Android. They can get directly accessed in XML via @drawable/filename whereby filename filename is the filename without extension. For example to access the hello.png file, you would use @drawable/hello

In code you can also access these drawables. Most views accept an resource ID as input parameter. For example the following code shows how to set a drawables as background to an ImageView.

ImageView imageView = (ImageView) findViewById(R.id.image);

3. Bitmaps and drawables PAGE TOP

Android allows you to use the Bitmap class for working with bitmaps. The Drawable class is more general, hence you frequently want to convert your bitmaps into drawables.

All bitmaps which are stored in the drawable folder can be directly used as a Drawable objects.

You can also load Bitmaps manually and convert them into Drawables objects. To load a bitmap from your assets folder or another folder you must create the Bitmap yourself. The following example code shows this for the assets folder.

// Get the AssetManager
    AssetManager manager = getAssets();

    // Read a Bitmap from Assets
    InputStream open = null;
    try {
      open = manager.open("logo.png");
      Bitmap bitmap = BitmapFactory.decodeStream(open);
      // Assign the bitmap to an ImageView in this layout
      ImageView view = (ImageView) findViewById(R.id.imageView1);
    } catch (IOException e) {
    } finally {
      if (open != null) {
        try {
        } catch (IOException e) {

You can also load the files from your drawable folder directly. The following code shows an example.

Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.ic_action_search);

You can create a scale bitmap based on a new weight and height definition in pixel.

Bitmap originalBitmap = <initial setup>;

Bitmap resizedBitmap = Bitmap.createScaledBitmap(originalBitmap, newWidth, newHeight, false);

To convert a bitmap into a Drawable you can use the following code.

# Convert Bitmap to Drawable
Drawable d = new BitmapDrawable(getResources(),bitmap);

4.1. Shape Drawables PAGE TOP

Shape Drawables are XML files which allow to define a geometric object with colors, borders and gradients which can get assigned to Views. The advantage of using XML Shape Drawables is that they automatically adjust to the correct size.

The following listing shows an example of a Shape Drawable.

<?xml version="1.0" encoding="UTF-8"?>
    android:color="#FFFFFFFF" />
    android:angle="90" />
    android:topRightRadius="7dp" />

You could for example assign that drawable to the background property of your layout.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" >


        android:layout_height="wrap_content" >

            android:text="@string/celsius" >

            android:text="@string/fahrenheit" >



4.2. State Drawables PAGE TOP

State drawables allow to define states. For each state a different drawable can get assigned to the View. For example the following defines different drawables for a button depending on its state.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

  <item android:drawable="@drawable/button_pressed"
    android:state_pressed="true" />
  <item android:drawable="@drawable/button_checked"
    android:state_checked="true" />
  <item android:drawable="@drawable/button_default" />


4.3. Transition Drawables PAGE TOP

Transition Drawables allow to define transitions which can be triggered in the coding.

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

final ImageView image = (ImageView) findViewById(R.id.image);
final ToggleButton button = (ToggleButton) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
  public void onClick(final View v) {
    TransitionDrawable drawable = (TransitionDrawable) image.getDrawable();
    if (button.isChecked()) {
    } else {

5. Animation Drawables PAGE TOP

You can also define an animation drawables and assign it to a View via the setBackgroundResource() method.

<!-- Animation frames are phase*.png files inside the
 res/drawable/ folder -->
 <animation-list android:id="@+id/selected" android:oneshot="false">
    <item android:drawable="@drawable/phase1" android:duration="400" />
    <item android:drawable="@drawable/phase2" android:duration="400" />
    <item android:drawable="@drawable/phase3" android:duration="400" />

ImageView img = (ImageView)findViewById(R.id.yourid);

 // Get the AnimationDrawable object.
 AnimationDrawable frameAnimation = (AnimationDrawable) img.getBackground();

 // Start the animation (looped playback by default).

Alternative you can implement a class which extends Drawable and implements Animatable.

6. 9 Patch Drawables PAGE TOP

9 Patch drawables are Drawables which have a one pixel additional border. On the top and left you define the area which should be scaled if the Drawable is to small for the View.

On the right and bottom side you define the area where a text should be placed if this Drawable is used on a View which can write text on it, e.g. a Button.

The ADT supplies the draw9patch program in the android-sdk/tools installation folder, which makes it easy to create 9 Patch drawables.

7. Custom Drawables PAGE TOP

You can also create custom Drawable, which can use the Canvas API for their display. For these drawables you can use the full Canvas API to design them to your need.

8. Exercise: Create Custom Drawables PAGE TOP

Create the following Android project called com.vogella.android.drawables.custom based on the BlankActivity template.

Create the following custom Drawable class.

package com.vogella.android.drawables.custom;

import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;

public class MyRoundCornerDrawable extends Drawable {

  private Paint paint;

  public MyRoundCornerDrawable(Bitmap bitmap) {

    BitmapShader shader;
    shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP,
    paint = new Paint();

  public void draw(Canvas canvas) {
    int height = getBounds().height();
    int width = getBounds().width();
    RectF rect = new RectF(0.0f, 0.0f, width, height);
    canvas.drawRoundRect(rect, 30, 30, paint);

  public void setAlpha(int alpha) {


  public void setColorFilter(ColorFilter cf) {


  public int getOpacity() {
    return 255;


To use it change your layout file to the following.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    tools:context=".MainActivity" >

        android:contentDescription="TODO" />


Change your MainActivity class to the following. The code assumes that you have a bitmap in your drawable folder called dog.png.

package com.vogella.android.drawables.custom;

import java.io.InputStream;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ImageView;

public class MainActivity extends Activity {

  protected void onCreate(Bundle savedInstanceState) {
    ImageView button = (ImageView) findViewById(R.id.image);
    InputStream resource = getResources().openRawResource(R.drawable.dog);
    Bitmap bitmap = BitmapFactory.decodeStream(resource);
    button.setBackground(new MyRoundCornerDrawable(bitmap));


Reference PAGE TOP


0 Comments Leave a comment

Please login in order to leave a comment.

Newest first

to your Chupamobile Account.

The Easiest way to Launch your next App or Game.

Join Chupamobile and get instant access to thousands of ready made App and Game Templates.

Creating an account means you’re okay with Chupamobile’s Terms of Service and Privacy Policy.