Image Resources

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 R.java 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(R.id.img);
img.setImageResource(R.drawable.android);

or like this to get the image as a drawable object

ImageView img2=(ImageView)findViewById(R.id.img2);
Drawable drawable=this.getResources().getDrawable(R.drawable.android);
img2.setBackgroundDrawable(drawable);

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(R.id.txt);
txt.setBackgroundResource(R.drawable.redBox);

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

or this
txt.setBackgroundResource(R.drawable.redBox);
notice that if the textview does not have text the background color will not appear.

Download a demo application from here

Related Posts by Categories

0 comments:

Post a Comment

Blog Archive

Powered by Blogger.