您的位置:首页 > 移动开发 > Android开发

Android获取验证码倒计时

2015-03-18 11:51 423 查看
获取验证码倒计时,切换页面或finish后,计时持续不间断的简易使用方法:

public class Example extends Activity{

private Button getCode_btn;//获取验证码按钮
public static CountDownTimer getCode_CDtimer;// 获取验证码计时器
public static long timeRemain;// 时间剩余记录

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.example);//布局文件自己自定义
getCode_btn = (Button) findViewById(R.id.getCode_btn);
if (Example .getCode_CDtimer != null) {// 如果获取验证码的计时器正在计时
Example .getCode_CDtimer.cancel();// 则获取当前剩余时间
timeRemain(Example .timeRemain);// 重新已剩余时间为基础计时
}
}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.getCode_btn:// 获取验证码按钮被点击
getCode_btn.setEnabled(false);// 按钮不可点击
timeRemain(60l);// 时间设置60秒计时
break;
}

/**
*
* @param 时间
*  获取验证码时间计时器初始化
*/

public void timeRemain(Long arg0) {

Example .getCode_CDtimer = new CountDownTimer(arg0 * 1000,
1000) {

@Override
public void onTick(long arg0) {
getCode_btn.setText(arg0 / 1000 + "秒");// 每隔1秒显示时间剩余
Example .timeRemain = arg0 / 1000;// 保存剩余时间
// Log.v("timer", Example .timeRemain +"");
if (arg0 <= 0) {
Example .timeRemain = 60l;// 计时完成剩余时间记录重置60s
}
}

@Override
public void onFinish() {
getCode_btn.setText("获取验证码");
getCode_btn.setEnabled(true);// 60秒结束后按钮可点击

}
}.start();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: