Skip to content

Instantly share code, notes, and snippets.

@VladSumtsov
Created January 20, 2015 15:43
Show Gist options
  • Save VladSumtsov/bd6cc420df7bdac92d30 to your computer and use it in GitHub Desktop.
Save VladSumtsov/bd6cc420df7bdac92d30 to your computer and use it in GitHub Desktop.
package com.aliens.utils;
import android.graphics.ColorFilter;
import android.graphics.LightingColorFilter;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
/**
* Created by vlad on 20.01.15.
*/
public class ColorStateListDrawable extends StateListDrawable {
private final Builder builder;
private ColorStateListDrawable(Builder builder) {
super();
this.builder = builder;
if (builder.pressedColor != 0) {
addState(new int[]{android.R.attr.state_pressed}, builder.drawable);
}
if (builder.selectedColor != 0) {
addState(new int[]{android.R.attr.state_selected}, builder.drawable);
}
if (builder.checkedColor != 0) {
addState(new int[]{android.R.attr.state_checked}, builder.drawable);
}
addState(new int[]{}, builder.drawable);
}
public static Builder with(Drawable drawable) {
return new Builder(drawable);
}
@Override
protected boolean onStateChange(int[] states) {
ColorFilter filter = null;
for (int state : states) {
if (state == android.R.attr.state_pressed) {
filter = new LightingColorFilter(builder.pressedColor, builder.pressedColor);
} else if (state == android.R.attr.state_selected) {
filter = new LightingColorFilter(builder.selectedColor, builder.selectedColor);
} else if (state == android.R.attr.state_checked) {
filter = new LightingColorFilter(builder.checkedColor, builder.checkedColor);
}
}
if (builder != null) {
if (filter != null) {
builder.drawable.setColorFilter(filter);
} else {
builder.drawable.clearColorFilter();
}
}
return super.onStateChange(states);
}
@Override
public boolean isStateful() {
return true;
}
public static class Builder {
private final Drawable drawable;
private int selectedColor;
private int pressedColor;
private int checkedColor;
public Builder(Drawable drawable) {
this.drawable = drawable;
}
public Builder selectedColor(int color) {
selectedColor = color;
return this;
}
public Builder pressedColor(int color) {
pressedColor = color;
return this;
}
public Builder checkedColor(int color) {
checkedColor = color;
return this;
}
public ColorStateListDrawable build() {
return new ColorStateListDrawable(this);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment