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
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.
ImageView class is used to display any kind of image resource in the android application either it can be android. graphics. Bitmap or android.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With