064e49165bf30f7b4b284495d4490b7dc76eb379.svn-base 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package com.hjq.widget;
  2. import android.annotation.SuppressLint;
  3. import android.content.Context;
  4. import android.os.Build;
  5. import android.support.annotation.Nullable;
  6. import android.support.annotation.RequiresApi;
  7. import android.util.AttributeSet;
  8. import android.widget.TextView;
  9. /**
  10. * desc : 验证码倒计时
  11. */
  12. @SuppressLint("AppCompatCustomView")
  13. public final class CountdownView extends TextView implements Runnable {
  14. private int mTotalTime = 60; // 倒计时秒数
  15. private static final String TIME_UNIT = "S"; // 秒数单位文本
  16. private int mCurrentTime; // 当前秒数
  17. private CharSequence mRecordText; // 记录原有的文本
  18. private boolean mFlag; // 标记是否重置了倒计控件
  19. public CountdownView(Context context) {
  20. super(context);
  21. }
  22. public CountdownView(Context context, @Nullable AttributeSet attrs) {
  23. super(context, attrs);
  24. }
  25. public CountdownView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
  26. super(context, attrs, defStyleAttr);
  27. }
  28. @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
  29. public CountdownView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
  30. super(context, attrs, defStyleAttr, defStyleRes);
  31. }
  32. /**
  33. * 设置倒计时总秒数
  34. */
  35. public void setTotalTime(int totalTime) {
  36. this.mTotalTime = totalTime;
  37. }
  38. /**
  39. * 重置倒计时控件
  40. */
  41. public void resetState() {
  42. mFlag = true;
  43. }
  44. @Override
  45. protected void onAttachedToWindow() {
  46. super.onAttachedToWindow();
  47. //设置点击的属性
  48. setClickable(true);
  49. }
  50. @Override
  51. protected void onDetachedFromWindow() {
  52. // 移除延迟任务,避免内存泄露
  53. removeCallbacks(this);
  54. super.onDetachedFromWindow();
  55. }
  56. @Override
  57. public boolean performClick() {
  58. boolean click = super.performClick();
  59. mRecordText = getText();
  60. setEnabled(false);
  61. mCurrentTime = mTotalTime;
  62. post(this);
  63. return click;
  64. }
  65. /**
  66. * {@link Runnable}
  67. */
  68. @Override
  69. public void run() {
  70. if (mCurrentTime == 0 || mFlag) {
  71. setText(mRecordText);
  72. setEnabled(true);
  73. mFlag = false;
  74. } else {
  75. mCurrentTime--;
  76. setText(mCurrentTime + "\t" + TIME_UNIT);
  77. postDelayed(this, 1000);
  78. }
  79. }
  80. }