话不多说上代码
public class CountdownTextView extends TextView {
private Timer timer;
public CountdownTextView(Context context) {
super(context);
}
public CountdownTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CountdownTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
//计时开始 时长单位s
public void start(TextView view,int duration) {
timer = new Timer();
timer.schedule(new CodeTimerTask(view,duration),0, 1000);
}
//页面销毁的时候调用
public void stop() {
if (timer != null) {
timer.cancel();
timer = null;
}
}
//计时器
class CodeTimerTask extends TimerTask {
private int time = 60;
private TextView getCode;
public CodeTimerTask(TextView textView,int duration) {
this.getCode =textView;
if(duration>0) {
time = duration;
}
}
@Override
public void run() {
post(new Runnable() {
@Override
public void run() {
if (time > 0) {
time --;
getCode.setText(time+"s");
getCode.setGravity(Gravity.END);
getCode.setEnabled(false);
} else {
getCode.setText("发送验证码");
getCode.setGravity(Gravity.CENTER);
getCode.setEnabled(true);
stop();
}
}
});
}
}
}
使用说明书:
<com.android.xc.account.view.CountdownTextView
android:id="@+id/get_code"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="@dimen/text_28px"
android:paddingLeft="@dimen/space_15px"
android:paddingRight="@dimen/space_15px"
android:textColor="@color/get_code_text_color"
android:text="获取验证码" />
private CountdownTextView getCode;
开始倒计时:
getCode.start(getCode,60);
注意:
在页面destroy的时候调用下stop方法
@Override
protected void onDestroy() {
getCode.stop();
super.onDestroy();
}