[转]永久告别Android的背景选择器Selector!无需切很多图了!

时间:2023-01-13 20:56:13
package com.zoke.custom.autobg;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.LightingColorFilter;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.Button; import com.zoke.custom.R; /**
* Android按钮显示不同状态无需多张图片的自定义控件
*
* @author Jack 2014-2-8
*
*
*/
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 defStyle) {
super(context, attrs, defStyle);
}
@Override
public void setBackgroundDrawable(Drawable d) {
// 替换背景图
AutoBgButtonBackgroundDrawable layer = new AutoBgButtonBackgroundDrawable(
d);
super.setBackgroundDrawable(layer);
} /**
* 按钮所使用的状态图
*/
protected class AutoBgButtonBackgroundDrawable extends LayerDrawable { // 按钮按下时所使用的颜色过滤器
protected ColorFilter _pressedFilter = new LightingColorFilter(
getContext().getResources().getColor(R.color.pressColor), 1);
// 按钮被禁用时的alpha值
protected int _disabledAlpha = 100; public AutoBgButtonBackgroundDrawable(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;
}
} }

博客原文