Skip to content

Instantly share code, notes, and snippets.

@klaasnotfound
Last active November 26, 2025 09:30
Show Gist options
  • Select an option

  • Save klaasnotfound/6f3441d8f32d4b93900c to your computer and use it in GitHub Desktop.

Select an option

Save klaasnotfound/6f3441d8f32d4b93900c to your computer and use it in GitHub Desktop.
package com.loclet.android.views;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ImageButton;
/**
* A simple extension of Android's ImageButton that automatically provides
* a "reasonable" appearance of the button in a pressed and disabled state.
* <p/>
* Modify {@link #BG_COLOR_ENABLED} and {@link #BG_COLOR_DISABLED} to
* your liking. These are the colors that "shine through" the foreground
* image when the button is pressed or disabled.
* <p/>
* If you have an image with transparency and don't want the rectangular
* button outline to show, set {@code android:background="@null"} in the
* XML layout.
*/
public class PressableImageButton extends ImageButton {
private static final int BG_COLOR_ENABLED = 0xff000000;
private static final int BG_COLOR_DISABLED = 0xffffffff;
private static final int ALPHA_ENABLED = 255;
private static final int ALPHA_DISABLED = 127;
private static final int ALPHA_PRESSED = 127;
private boolean transparentBackground;
public PressableImageButton(Context context) {
super(context);
init();
}
public PressableImageButton(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public PressableImageButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
if (getBackground() == null)
transparentBackground = true;
if (!transparentBackground)
setBackgroundColor(BG_COLOR_ENABLED);
setPadding(0, 0, 0, 0);
if (getDrawable() != null)
getDrawable().setAlpha(ALPHA_ENABLED);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (isEnabled()) {
if (event.getAction() == MotionEvent.ACTION_DOWN)
getDrawable().setAlpha(ALPHA_PRESSED);
else if (event.getAction() == MotionEvent.ACTION_UP)
getDrawable().setAlpha(ALPHA_ENABLED);
}
return super.onTouchEvent(event);
}
@Override
public void setEnabled(boolean enabled) {
if (enabled) {
if (!transparentBackground)
setBackgroundColor(BG_COLOR_ENABLED);
if (getDrawable() != null)
getDrawable().setAlpha(ALPHA_ENABLED);
} else {
if (!transparentBackground)
setBackgroundColor(BG_COLOR_DISABLED);
if (getDrawable() != null)
getDrawable().setAlpha(ALPHA_DISABLED);
}
super.setEnabled(enabled);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment