ImageView - draw translucent color on top for its focused state?

android

Solution

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`.

Problem

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

Original source