Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

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

like image 398
user291701 Avatar asked May 23 '12 16:05

user291701


2 Answers

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.

like image 165
wsanville Avatar answered Sep 20 '22 14:09

wsanville


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);
    }
like image 43
Lukas Hanacek Avatar answered Sep 19 '22 14:09

Lukas Hanacek