Skip to content

Instantly share code, notes, and snippets.

@nobre84
Created February 13, 2015 18:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nobre84/bdd652f875222e406061 to your computer and use it in GitHub Desktop.
Save nobre84/bdd652f875222e406061 to your computer and use it in GitHub Desktop.
StateListDrawable that applies a ColorFilter with the desired color / state configuration
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.util.StateSet;
/**
* Created by Rafael Nobre on 12/02/15.
*/
public class ColorFilteredStateDrawable extends StateListDrawable {
private final int[][] states;
private final int[] colors;
public ColorFilteredStateDrawable(Drawable drawable, int[][] states, int[] colors) {
super();
drawable.mutate();
this.states = states;
this.colors = colors;
for (int i = 0; i < states.length; i++) {
addState(states[i], drawable);
}
}
@Override
protected boolean onStateChange(int[] states) {
if (this.states != null) {
for (int i = 0; i < this.states.length; i++) {
if (StateSet.stateSetMatches(this.states[i], states)) {
super.setColorFilter(this.colors[i], PorterDuff.Mode.MULTIPLY);
return super.onStateChange(states);
}
}
super.clearColorFilter();
}
return super.onStateChange(states);
}
@Override
public boolean isStateful() {
return true;
}
}
Drawable drawable = getResources().getDrawable(R.drawable.ic_base_white_drawable).mutate();
int[][] states = new int[][] { new int[]{android.R.attr.state_pressed} , StateSet.WILD_CARD };
int[] colors = new int[] {getResources().getColor(R.color.color_pressed), getResources().getColor(R.color.color_normal)};
ColorFilteredStateDrawable selector = new ColorFilteredStateDrawable(drawable, states, colors);
imageView.setImageDrawable(selector);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment