Created
February 13, 2015 18:31
-
-
Save nobre84/bdd652f875222e406061 to your computer and use it in GitHub Desktop.
StateListDrawable that applies a ColorFilter with the desired color / state configuration
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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