先看效果
基于handler实现, 比timertask更省内存.
/**
* Created by jin on 2017/4/17.
* 倒计时按钮, 发短信
*/
public class CountdownButton extends Button{
private GradientDrawable shapeBg;//shape背景
private int mDisablecolor;//不可点击时背景颜色
private int mNormalcolor;//正常的背景颜色.
private int DEFAULT_TIME = 60;//倒计时时间
public CountdownButton(Context context) {
this(context, null);
}
public CountdownButton(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.buttonStyle);
}
public CountdownButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private String beforeText = "获取验证码";
private void init(Context context, AttributeSet attrs) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CountDownTimerButton);
// 默认背景
mNormalcolor = a.getColor(R.styleable.CountDownTimerButton_normalcolor, 0xffff0000);
// 不可点击时的背景
mDisablecolor = a.getColor(R.styleable.CountDownTimerButton_disablecolor, 0xff00ff00);
float dimension = a.getDimension(R.styleable.CountDownTimerButton_corner, UiUtils.dip2px(context, 8));
a.recycle();
shapeBg = new GradientDrawable();
shapeBg.setColor(mNormalcolor);
shapeBg.setCornerRadius(dimension);
if (!TextUtils.isEmpty(this.getText().toString().trim())) {
this.beforeText = this.getText().toString().trim();
}
this.setBackground(shapeBg);
this.setText(beforeText);
}
public void startCountdown() {
mHandler.sendEmptyMessageDelayed(0, 1000);
shapeBg.setColor(mDisablecolor);
this.setBackground(shapeBg);
this.setClickable(false);
}
private Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 0:
if (DEFAULT_TIME >= 0) {
CountdownButton.this.setText(String.format("重新发送(%d)", DEFAULT_TIME--));
mHandler.sendEmptyMessageDelayed(0, 1000);
} else {
CountdownButton.this.setClickable(true);
shapeBg.setColor(mNormalcolor);
CountdownButton.this.setBackground(shapeBg);
CountdownButton.this.setText(beforeText);
DEFAULT_TIME = 60;
mHandler.removeCallbacksAndMessages(null);
}
break;
}
}
};
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mHandler.removeCallbacksAndMessages(null);
}
}
values/attrs中
<declare-styleable name="CountDownTimerButton">
<attr name="normalcolor" format="color" />
<attr name="disablecolor" format="color" />
<attr name="corner" format="dimension"/>
</declare-styleable>
使用方法
xml中:
和普通button一样定义,只是多了三个属性
app:normalcolor="@color/themeOrange"
app:disablecolor="@color/gray"
app:corner="8dp"
分别是正常状态颜色/点击后的颜色/圆角大小
代码中:
在适当的时机调用startCountdown()方法即可.
by the way
xml中按钮可添加style="?android:attr/borderlessButtonStyle"
这个属性屏蔽点击阴影