Android -- 一个自定义Button(不需要手写selector)

效果图

state_button.gif

在写Button时经常需要添加一个selector来作为背景,设置手指按下抬起、是否可用的状态,项目中往往会写很多的selector,StateButton就是来解决这个问题的。

创建shape

这里是用代码创建一个GradientDrawable,并添加背景颜色、圆角半径、边框。

添加自定义属性


    
    
    
    
    
    
    
    

获取属性并添加背景

//圆角半径
int cornerRadius = 0;
//边框宽度
int borderStroke = 0;
//边框颜色
int borderColor = 0;
//enable为false时的颜色
int unableColor = 0;

//背景shape
GradientDrawable shape;

int colorId;
int alpha;
boolean unable;

public StateButton(Context context) {
    this(context, null);
}

public StateButton(Context context, AttributeSet attrs) {
    super(context, attrs);

    if(shape == null) {
        shape = new GradientDrawable();
    }

    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.StateButton, 0, 0);

    cornerRadius = (int) a.getDimension(R.styleable.StateButton_corner_radius, 0);
    borderStroke = (int) a.getDimension(R.styleable.StateButton_border_stroke, 0);
    borderColor = a.getColor(R.styleable.StateButton_border_color, 0);
    unableColor = a.getColor(R.styleable.StateButton_unable_color, Color.GRAY);

    ColorDrawable buttonColor = (ColorDrawable) getBackground();
    colorId = buttonColor.getColor();
    alpha = 255;

    if(unable) {
        shape.setColor(unableColor);
    }else{
        shape.setColor(colorId);
    }

    a.recycle();

    init();
}

public void init() {
    //设置圆角半径
    shape.setCornerRadius(cornerRadius);
    //设置边框宽度和颜色
    shape.setStroke(borderStroke, borderColor);
    //将GradientDrawable设置为背景
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        setBackground(shape);
    } else {
        setBackgroundDrawable(shape);
    }

}

设置手指按下的状态

这里是重写setPressed方法,手指按下时背景透明度设为原来的0.6。

@Override
public void setPressed(boolean pressed) {
    super.setPressed(pressed);
    if(pressed){
        shape.setAlpha((int) (alpha*0.6));
        init();
    }else{
        shape.setAlpha(alpha);
        init();
    }
}

设置enable等于false的状态

这里重写setEnabled方法,重新设置背景颜色

@Override
public void setEnabled(boolean enabled) {
    super.setEnabled(enabled);
    unable = !enabled;
    if(shape != null) {
        shape = new GradientDrawable();
        if(unable) {
            shape.setColor(unableColor);
        }else{
            shape.setColor(colorId);
        }
        init();
    }
}

到这里就结束了,完整代码请点击源码观看
源码

你可能感兴趣的:(Android -- 一个自定义Button(不需要手写selector))