现在很多app都有发送短信验证的功能,在用户点击按钮发送验证码以后,就会再按钮上显示倒计时,在此期间点击按钮是无效的,在倒计时完成以后可以再次点击,我通过集成CountDownTimer来实现这个功能。
封装工具类
public class MyCountDownTimer extends CountDownTimer {
private Button btn;
private String msg;
/**
*
* @param millisInFuture
* 倒计时总时间
* @param countDownInterval
* 间隔时间
* @param button
* 点击的空间,这里用Button
* @param msg
* 倒计时完成以后显示的文字
*/
public MyCountDownTimer(long millisInFuture, long countDownInterval,
Button button, String msg) {
super(millisInFuture, countDownInterval);
this.btn = button;
this.msg = msg;
}
//计时过程中触发
@Override
public void onTick(long millisUntilFinished) {
btn.setEnabled(false);
btn.setText(millisUntilFinished / 1000 + "s");
}
//计时完成以后触发
@Override
public void onFinish() {
btn.setEnabled(true);
btn.setText(msg);
}
}
界面上显示
public class MainActivity extends Activity {
private Button btn;
private MyCountDownTimer timer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn);
timer = new MyCountDownTimer(60 * 1000, 1000, btn, getResources()
.getString(R.string.message));
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
timer.start();
}
});
}
}