Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ColorDrawable with ImageView?

Tags:

android

I have a layout with an ImageView defined like:

<ImageView
  android:layout_width="45dip"
  android:layout_height="45dip"
  android:scaleType="fitXY" />

now I just want to set the imageview to be a static color, like red or green. I'm trying:

ColorDrawable cd = new ColorDrawable("FF0000");
cd.setAlpha(255);
ImageView iv = ...;
iv.setImageDrawable(cd);

the imageview is just empty though, no color. The 45dip space is being used up though. What do I need to do to get the color to be rendered?

Thanks

like image 808
user246114 Avatar asked Mar 30 '10 20:03

user246114


People also ask

What is ColorDrawable?

android.graphics.drawable.ColorDrawable. A specialized Drawable that fills the Canvas with a specified color. Note that a ColorDrawable ignores the ColorFilter. It can be defined in an XML file with the <color> element.

What is the use of ImageView?

ImageView class is used to display any kind of image resource in the android application either it can be android. graphics. Bitmap or android.


1 Answers

Looking at the constructor for ColorDrawable I don't see a version that takes a string like in your example. I see one that takes an int. Try this:

ColorDrawable cd = new ColorDrawable(0xffff0000);

or this for string:

ColorDrawable cd = new ColorDrawable(Color.parseColor("#FFFF0000"));

Notice I used 8 hex digits, not 6 like in your example. This sets the alpha value as well.

Edit: Looking back at some of my own code where I've done something similar, I always used setBackgroundDrawable() instead of setImageDrawable() to initialize an ImageView with a solid color. Not sure if that would make a difference.

like image 114
Mark B Avatar answered Sep 20 '22 00:09

Mark B