I have an imageview on which I have set a bitmap fetched from an url. On the imageview I have set an onClickListener which opens up a dialog.
I want to somehow change the tint (make it darker) when the imageview is pressed upon to provide a sort of button click like feel.
What do you suggest?
One way would be to use a combination of a
ColorFilter
and aColorStateList
that contains your tint color for when the button is pressed. The xml for theColorStateList
in the res/color directory would look like this:button_pressed.xml
where
@color/pressed_color
is your tint color (which should be partially transparent). Then in yourImageView
subclass, you apply the color by overridingdrawableStateChanged()
.Any time the button's state changes, this code is called and will automatically set the tint as appropriate.
I'd have to test it out, but you should be able to set an xml with that behaviour as the ImageView drawable, and then set your bitmap as the ImageView background.
This code snippet worked for me:
happydude's answer is the most elegant way to handle this but unfortunately (as pointed out in the comments) the source code for ImageView only accepts an integer (solid colour). Issue 18220 has been around for a couple years addressing this, I've posted a workaround there that I'll summarize here:
Extend ImageView and wrap drawableStateChanged() with code that sets the tint based on the new state:
TintableImageView.java
Define a custom attribute:
attrs.xml
Use the widget and custom attribute with your local namespace instead of Android's:
example_layout.xml
You can then use a colour selector like happydude suggested:
color_selector.xml
For me a simple solution is working, using setAlpha(180) in onClick event make the image darker, giving the user a feedback that it was clicked or touched.
Regarding your XML layout, nothing special.