Skip to content

Instantly share code, notes, and snippets.

@richardleggett
Last active December 16, 2015 01:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richardleggett/5356119 to your computer and use it in GitHub Desktop.
Save richardleggett/5356119 to your computer and use it in GitHub Desktop.
Android ImageButton that automatically darkens on press, as with iOS UIButton's default highlight. The draw() method is overridden to alpha out the button if disabled. The idea is you quickly get button states without providing state list drawables.
// if you're wanting to put these inside an AdapterView, replace ImageButton below with ImageView
public class AutoHighlightImageButton extends ImageButton {
private boolean mIsPressed;
public AutoHighlightImageButton(Context context) {
super(context);
init();
}
public AutoHighlightImageButton(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public AutoHighlightImageButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
mIsPressed = false;
}
@Override
public void draw(Canvas canvas) {
// alpha to 0.5 when disabled
canvas.saveLayerAlpha(null, isEnabled() ? 255 : 127, Canvas.ALL_SAVE_FLAG);
super.draw(canvas);
canvas.restore();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if(isEnabled()) {
if (event.getAction() == MotionEvent.ACTION_DOWN && !mIsPressed) {
setColorFilter(0x99000000);
mIsPressed = true;
return true;
} else if (event.getAction() == MotionEvent.ACTION_CANCEL || event.getAction() == MotionEvent.ACTION_UP) {
if(mIsPressed) {
setColorFilter(Color.TRANSPARENT);
mIsPressed = false;
}
}
}
return super.onTouchEvent(event);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment