Android短信验证码倒计时

 2023-09-05 阅读 148 评论 0

摘要:有两种实现方法 1、第一种方式:Timer /*** Description:自定义Timer* <p>* Created by Mjj on 2016/12/4.*/public class TimeCount extends CountDownTimer {private Button button;//参数依次为总时长,和计时的时间间隔public TimeCount(Button button,

有两种实现方法

1、第一种方式:Timer

/*** Description:自定义Timer* <p>* Created by Mjj on 2016/12/4.*/public class TimeCount extends CountDownTimer {private Button button;//参数依次为总时长,和计时的时间间隔public TimeCount(Button button, long millisInFuture, long countDownInterval) {super(millisInFuture, countDownInterval);this.button = button;}//计时过程显示
  @Overridepublic void onTick(long millisUntilFinished) {String time = "(" + millisUntilFinished / 1000 + ")秒";setButtonInfo(time, "#c1c1c1", false);}//计时完毕时触发
  @Overridepublic void onFinish() {setButtonInfo("重新获取", "#f95353", true);}/*** 验证按钮在点击前后相关设置** @param content 要显示的内容* @param color  颜色值* @param isClick 是否可点击*/private void setButtonInfo(String content, String color, boolean isClick) {button.setText(content);button.setBackgroundColor(Color.parseColor(color));button.setClickable(isClick);}
}

2、第二种方式:Handler

/*** 第二种方式:使用Handler* <p>* 静态内部类:避免内存泄漏*/private static class MyHandler extends Handler {private final WeakReference<MainActivity> weakReference;public MyHandler(MainActivity activity) {weakReference = new WeakReference<MainActivity>(activity);}@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);MainActivity activity = weakReference.get();if (activity != null) {switch (msg.what) {case 0:if (msg.arg1 == 0) {btn2.setText("重新获取");btn2.setBackgroundColor(Color.parseColor("#f95353"));btn2.setClickable(true);} else {btn2.setText("(" + msg.arg1 + ")秒");btn2.setBackgroundColor(Color.parseColor("#c1c1c1"));btn2.setClickable(false);}break;}}}}/*** 监听按钮下直接调用即可*/private void sendMessageClick() {new Thread(new Runnable() {@Overridepublic void run() {for (int i = 59; i >= 0; i--) {Message msg = myHandler.obtainMessage();msg.arg1 = i;myHandler.sendMessage(msg);try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}}).start();}

 

转载于:https://www.cnblogs.com/AganRun/p/8118861.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/1/83.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息