在开发时, 经常会写获取验证码倒计时这个控件, 因为刚接手别人的项目, 发现该项目中使用的控件有问题, 于是自己写了个
思路: 在button内实现onClick方法, 在onClick内处理倒计时等事情
效果图:
布局代码:
activity代码:
view代码:
public class IdentifyingCodeButton extends android.support.v7.widget.AppCompatButton {
private Handler handler;
private int time;
private Drawable canClickBackground;//可点击的时候背景
private Drawable cannotClickBackground;//不可点击的时候背景
private String defaultText;//默认文字
private int canClickTextColor = -1;//可点击时文字颜色
private int cannottClickTextColor = -1;//不可可点击时文字颜色
private int countTime = 60;
public IdentifyingCodeButton(Context context) {
this(context,null);
}
public IdentifyingCodeButton(Context context, AttributeSet attrs) {
this(context,attrs,0);
}
public IdentifyingCodeButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
handler = new Handler(){
@Override
public void handleMessage(Message msg) {
countDown();
}
};
defaultText = this.getText().toString().trim();
if (defaultText == null || defaultText.length() == 0){
defaultText = "获取验证码";
this.setText(defaultText);
}
this.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
time = countTime;
handler.sendEmptyMessage(0);
}
});
}
private void countDown(){
time--;
if (time != 0){
this.setText(time + "秒");
this.setClickable(false);
if (cannotClickBackground == null){
this.setBackgroundColor(Color.GRAY);
}else{
this.setBackground(cannotClickBackground);
}
if (cannottClickTextColor != -1){
this.setTextColor(cannottClickTextColor);
}
handler.sendEmptyMessageDelayed(0,1000);
}else{
this.setClickable(true);
this.setText(defaultText);
if (canClickBackground != null)
this.setBackground(canClickBackground);
if (canClickTextColor != -1){
this.setTextColor(canClickTextColor);
}
}
}
//设置倒计时时长 默认60秒
public void setTime(int time){
this.time = time;
this.countTime = time;
}
public void setCannotClickBackground(Drawable cannotClickBackground){
this.cannotClickBackground = cannotClickBackground;
}
public void setCanClickBackground(Drawable canClickBackground){
this.canClickBackground = canClickBackground;
}
public void setCanClickTextColor(int canClickTextColor) {
this.canClickTextColor = canClickTextColor;
}
public void setCannottClickTextColor(int cannottClickTextColor) {
this.cannottClickTextColor = cannottClickTextColor;
}
}
原理很简单, 不同情况使用可以再修改完善