Skip to content

Instantly share code, notes, and snippets.

@mrleolink
Last active August 29, 2015 13:55
Show Gist options
  • Select an option

  • Save mrleolink/8780750 to your computer and use it in GitHub Desktop.

Select an option

Save mrleolink/8780750 to your computer and use it in GitHub Desktop.
A really useful gist which helps to create pressed state for Android's Button/ImageButton without using additional drawbles
package net.leolink.android.gist;
public class MultiStateDrawable extends LayerDrawable {
// The color filter to apply when the button is pressed
protected ColorFilter _pressedFilter = new LightingColorFilter(Color.GRAY, 1);
public MultiStateDrawable(Drawable d) {
super(new Drawable[] { d });
}
@Override
protected boolean onStateChange(int[] states) {
boolean enabled = false;
boolean pressed = false;
for (int state : states) {
if (state == android.R.attr.state_enabled)
enabled = true;
else if (state == android.R.attr.state_pressed)
pressed = true;
}
mutate();
if (enabled) {
if (pressed) {
setColorFilter(_pressedFilter);
} else {
setColorFilter(null);
}
} else {
setColorFilter(_pressedFilter);
}
invalidateSelf();
return super.onStateChange(states);
}
@Override
public boolean isStateful() {
return true;
}
}
package net.leolink.android.gist;
public class StatefulImageButton extends ImageButton {
public StatefulImageButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public StatefulImageButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
public StatefulImageButton(Context context) {
super(context);
}
@SuppressLint("NewApi")
@Override
public void setBackground(Drawable background) {
MultiStateDrawable msd = new MultiStateDrawable(background);
if (Build.VERSION.SDK_INT < 16)
super.setBackgroundDrawable(msd);
else
super.setBackground(msd);
}
@Override
public void setImageDrawable(Drawable drawable) {
MultiStateDrawable msd = new MultiStateDrawable(drawable);
super.setImageDrawable(msd);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment