本文主要是介绍安卓验证码倒计时的实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
构造方法
public CountDownTimer (long millisInFuture, long countDownInterval)
参数
millisInFuture 从开始调用start()到倒计时完成并onFinish()方法被调用的毫秒数。(译者注:倒计时时间,单位毫秒)
countDownInterval 接收onTick(long)回调的间隔时间。(译者注:单位毫秒)
公共方法如下:
取消倒计时(译者:取消后,再次启动会重新开始倒计时)
public final void cancel ()
倒计时完成时被调用
public abstract void onFinish ()
固定间隔被调用
public abstract void onTick (long millisUntilFinished)参数 millisUntilFinished 倒计时剩余时间。
启动倒计时
public synchronized final CountDownTimer start ()
新建一个类继承CountDownTimer,重写onFinish()以及onTick()方法。
public class MyCountdown extends CountDownTimer {private Button mButton;public MyCountdown(Button button, long millisInFuture,long countDownInterval) {super(millisInFuture, countDownInterval);mButton = button;
}@Override
public void onFinish() {// 获取 验证码按钮可点击setButtonEnable();}@Override
public void onTick(long millisUntilFinished) {// 获取验证码按钮不可点击,倒计时开始setButtonUnEnable(millisUntilFinished);}@SuppressWarnings("deprecation")
private void setButtonEnable() {mButton.setEnabled(true);mButton.setText("重新获取");mButton.setBackgroundDrawable(MyApplication.getInstance().getResources().getDrawable(R.drawable.shape_button_red));}@SuppressWarnings("deprecation")
public void setButtonUnEnable(long millisUntilFinished) {mButton.setEnabled(false);mButton.setText("重新获取(" + millisUntilFinished / 1000 + ")秒");mButton.setBackgroundDrawable(MyApplication.getInstance().getResources().getDrawable(R.drawable.shape_button_gray));
}}
用到两个样式xml。
shapebuttonred.xml
<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android" > <corners android:radius="3.0dip" /> <solid android:color="@color/ycode"></solid></shape>
shapebuttongray.xml
<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android" ><corners android:radius="3.0dip" />
<solid android:color="@color/gary" /> </shape>
调用:
1.先声明
private MyCountdown mCounter;
2.实例化并start
mCounter = new MyCountdown(btn_reg_getcode, 60000, 1000);
mCounter.start();
这篇关于安卓验证码倒计时的实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!