一般我们给button或者imageview设置点击效果时,会使用一个xml的选择器selector。但是整个应用下来会创建很多个xml,甚至很多图片。
一般我们要得点击效果只是让透明度有些变化而已,那么针对透明度变化自定义一个组件。
public class AutoBgButton extends Button {
public AutoBgButton(Context context) {
super(context);
}
public AutoBgButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
public AutoBgButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public void setBackground(Drawable d) {
// Replace the original background drawable (e.g. image) with a
// LayerDrawable that
// contains the original drawable.
SAutoBgButtonBackgroundDrawable layer = new SAutoBgButtonBackgroundDrawable(d);
super.setBackground(layer);
}
protected class SAutoBgButtonBackgroundDrawable extends LayerDrawable {
// The color filter to apply when the button is pressed
protected ColorFilter _pressedFilter = new LightingColorFilter(Color.LTGRAY, 1);
// Alpha value when the button is disabled
protected int _disabledAlpha = 200;
public SAutoBgButtonBackgroundDrawable(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 && pressed) {
setColorFilter(_pressedFilter);
} else if (!enabled) {
setColorFilter(null);
setAlpha(_disabledAlpha);
} else {
setColorFilter(null);
}
invalidateSelf();
return super.onStateChange(states);
}
@Override
public boolean isStateful() {
return true;
}
}
}
也可以自定义imageview实现相同的效果。透明度最大为255。
>
>
>
>
>
参考文章 http://stormzhang.com/android/2013/09/21/android-autobg-imageview/