Android中注册获取验证码倒计时按钮

时间:2022-01-14 09:53:15
  1. public class CountDownTimerUtils extends CountDownTimer {
  2. private TextView mTextView;
  3. /**
  4. * @param textView          The TextView
  5. *
  6. *
  7. * @param millisInFuture    The number of millis in the future from the call
  8. *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
  9. *                          is called.
  10. * @param countDownInterval The interval along the way to receiver
  11. *                          {@link #onTick(long)} callbacks.
  12. */
  13. public CountDownTimerUtils(TextView textView, long millisInFuture, long countDownInterval) {
  14. super(millisInFuture, countDownInterval);
  15. this.mTextView = textView;
  16. }
  17. @Override
  18. public void onTick(long millisUntilFinished) {
  19. mTextView.setClickable(false); //设置不可点击
  20. mTextView.setText(millisUntilFinished / 1000 + "秒后可重新发送");  //设置倒计时时间
  21. mTextView.setBackgroundResource(R.drawable.bg_identify_code_press); //设置按钮为灰色,这时是不能点击的
  22. /**
  23. * 超链接 URLSpan
  24. * 文字背景颜色 BackgroundColorSpan
  25. * 文字颜色 ForegroundColorSpan
  26. * 字体大小 AbsoluteSizeSpan
  27. * 粗体、斜体 StyleSpan
  28. * 删除线 StrikethroughSpan
  29. * 下划线 UnderlineSpan
  30. * 图片 ImageSpan
  31. * http://blog.csdn.net/ah200614435/article/details/7914459
  32. */
  33. SpannableString spannableString = new SpannableString(mTextView.getText().toString());  //获取按钮上的文字
  34. ForegroundColorSpan span = new ForegroundColorSpan(Color.RED);
  35. /**
  36. * public void setSpan(Object what, int start, int end, int flags) {
  37. * 主要是start跟end,start是起始位置,无论中英文,都算一个。
  38. * 从0开始计算起。end是结束位置,所以处理的文字,包含开始位置,但不包含结束位置。
  39. */
  40. spannableString.setSpan(span, 0, 2, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);//将倒计时的时间设置为红色
  41. mTextView.setText(spannableString);
  42. }
  43. @Override
  44. public void onFinish() {
  45. mTextView.setText("重新获取验证码");
  46. mTextView.setClickable(true);//重新获得点击
  47. mTextView.setBackgroundResource(R.drawable.bg_identify_code_normal);  //还原背景色
  48. }
  49. }

使用:

CountDownTimerUtils mCountDownTimerUtils = new CountDownTimerUtils(mButton, 60000, 1000);

mCountDownTimerUtils.start();