看了简书上的一片关于CountDownButton的文章:Hyena-CountDownButton-倒计时按钮
用了里面的思路自己写了下。
主要代码
public class CountDownButton extends Button {
private String text;
private String content;
public CountDownButton(Context context) {
this(context, null);
}
public CountDownButton(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CountDownButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
TypedArray typedArray = context.getResources().obtainAttributes(attrs, R.styleable.CountDownButton);
long countDownInterval = typedArray.getInteger(R.styleable.CountDownButton_countDownInterval, 1)*1000;
long millisInFuture = typedArray.getInteger(R.styleable.CountDownButton_millisInFuture, 5)*1000;
timer = new MyCount(millisInFuture, countDownInterval);
typedArray.recycle();
}
public void start() {
content = getText().toString().trim();
timer.start();
this.setEnabled(false);
}
public void cancel() {
timer.cancel();
}
private MyCount timer;
private class MyCount extends CountDownTimer {
/**
* @param millisInFuture The number of millis in the future from the call
* to {@link #start()} until the countdown is done and {@link #onFinish()}
* is called.
* @param countDownInterval The interval along the way to receive
* {@link #onTick(long)} callbacks.
*/
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onTick(long millisUntilFinished) {
String time = "" + (millisUntilFinished / 1000);
Log.i(TAG, "onTick: "+time);
CountDownButton.this.setText(time);
}
private static final String TAG = "MyCount";
@Override
public void onFinish() {
CountDownButton.this.setText(content);
CountDownButton.this.setEnabled(true);
}
}
}
自定义属性
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CountDownButton">
<attr name="millisInFuture" format="integer"/>
<attr name="countDownInterval" format="integer"/>
</declare-styleable>
</resources>
布局
<com.nevermore.rounrect.CountDownButton
android:layout_centerInParent="true"
android:id="@+id/cdb"
android:background="@drawable/bg_count_down"
android:text="发送验证码"
android:gravity="center"
app:millisInFuture="20"
app:countDownInterval="1"
android:layout_width="110dp"
android:padding="15dp"
android:layout_height="wrap_content" />
bg_count_down
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="true">
<shape android:shape="rectangle">
<corners android:radius="8dp"/>
<solid android:color="#2eb7ed"/>
</shape>
</item>
<item android:state_enabled="false">
<shape android:shape="rectangle">
<corners android:radius="8dp"/>
<solid android:color="#999999"/>
</shape>
</item>
</selector>