I have an ImageView, I'd like a selector such that when the user clicks or otherwise has focus, a translucent color is drawn on top of the ImageView content. I'm not sure if this is possible with selectors (which I've been defining ok in the past with static drawables).
But basically I have a listview with imageview instances in each row, and wanted to do something like:
ImageView iv = ...;
iv.setBitmapDrawable(bitmapLoadedFromInternets()); // dynamic content
iv.setClickStateOverlayColor(0x33ff0000); // ?
Usually ImageView only takes a single drawable via setBitmapDrawable(), but a selector (1) swaps out the drawable for the different click states, whereas I just want a color overlay drawn, and (2) the off state is a dynamic bitmap, so I can't reference that from a selector definition.
Thanks
You can do that pretty easily if you make your own subclass of ImageView
. The method to use is setColorFilter. Something like this will do it:
public class ImageView extends android.widget.ImageView
{
public ImageView(Context context)
{
super(context);
}
public ImageView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public ImageView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN && isEnabled())
setColorFilter(0x33ff0000, PorterDuff.Mode.MULTIPLY); //your color here
if(event.getAction() == MotionEvent.ACTION_UP)
setColorFilter(null);
return super.onTouchEvent(event);
}
}
You can then use it in your XML layouts just by referring to it fully qualified like my.package.ImageView
instead of just ImageView
.
The solution with onTouch didnt work for me for multiple reasons but gave me hints on how to do it so that it works for me. I just overriden another method in the ImageView.
@Override
public void setPressed(boolean pressed) {
if (pressed) {
setColorFilter(0x55000000, PorterDuff.Mode.SRC_ATOP);
}
else {
clearColorFilter();
}
super.setPressed(pressed);
}
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