happydude's answer is the most elegant way to handle this, but unfortunately (as indicated in the comments) the source code for ImageView only accepts an integer (solid color). Problem 18220 has been doing this for a couple of years, I posted a workaround, which I will provide here:
Extend ImageView and wrap drawableStateChanged () with code that sets the hue based on the new state:
TintableImageView.java
package com.example.widgets; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.TypedArray; import android.util.AttributeSet; import android.widget.ImageView; import com.example.R; public class TintableImageView extends ImageView { private ColorStateList tint; public TintableImageView(Context context) { super(context); } public TintableImageView(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs, 0); } public TintableImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context, attrs, defStyle); } private void init(Context context, AttributeSet attrs, int defStyle) { TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TintableImageView, defStyle, 0); tint = a.getColorStateList(R.styleable.TintableImageView_tint); a.recycle(); } @Override protected void drawableStateChanged() { super.drawableStateChanged(); if (tint != null && tint.isStateful()) updateTintColor(); } public void setColorFilter(ColorStateList tint) { this.tint = tint; super.setColorFilter(tint.getColorForState(getDrawableState(), 0)); } private void updateTintColor() { int color = tint.getColorForState(getDrawableState(), 0); setColorFilter(color); } }
Define a custom attribute:
attrs.xml
<?xml version="1.0" encoding="UTF-8"?> <resources> <declare-styleable name="TintableImageView"> <attr name="tint" format="reference|color" /> </declare-styleable> </resources>
Use the widget and custom attribute with your local namespace, not with Android:
example_layout.xml
<?xml version="1.0" encoding="UTF-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <com.example.widgets.TintableImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/example" app:tint="@color/color_selector"/> </LinearLayout>
Then you can use the color selector as happydude suggested:
color_selector.xml
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:color="@color/pressed_color"/> <item android:color="#00000000"/> </selector>
Stephen Kidson Sep 10 '13 at 16:58 2013-09-10 16:58
source share