效果圖
state_button.gif
在寫B(tài)utton時經(jīng)常需要添加一個selector來作為背景儡炼,設(shè)置手指按下抬起查蓉、是否可用的狀態(tài)豌研,項目中往往會寫很多的selector,StateButton就是來解決這個問題的鬼佣。
創(chuàng)建shape
這里是用代碼創(chuàng)建一個GradientDrawable,并添加背景顏色晶衷、圓角半徑晌纫、邊框锹漱。
添加自定義屬性
<declare-styleable name="StateButton">
<!--圓角半徑-->
<attr name="corner_radius" format="dimension" />
<!--邊框顏色-->
<attr name="border_color" format="color" />
<!--邊框?qū)挾?->
<attr name="border_stroke" format="dimension" />
<!--不可用時的顏色-->
<attr name="unable_color" format="color" />
</declare-styleable>
獲取屬性并添加背景
//圓角半徑
int cornerRadius = 0;
//邊框?qū)挾?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() {
//設(shè)置圓角半徑
shape.setCornerRadius(cornerRadius);
//設(shè)置邊框?qū)挾群皖伾? shape.setStroke(borderStroke, borderColor);
//將GradientDrawable設(shè)置為背景
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
setBackground(shape);
} else {
setBackgroundDrawable(shape);
}
}
設(shè)置手指按下的狀態(tài)
這里是重寫setPressed方法,手指按下時背景透明度設(shè)為原來的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();
}
}
設(shè)置enable等于false的狀態(tài)
這里重寫setEnabled方法辩诞,重新設(shè)置背景顏色
@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();
}
}
到這里就結(jié)束了纺涤,完整代碼請點擊源碼觀看
源碼