项目中我们经常会用获取短信验证码之后的一个倒计时,今天给大家分享个用CountDownTimer实现,代码是最好的老师,我会在每行代码上都做好注释.配置文件比较简单 这里只写java代码了
package com.bjttxs.csdn;
import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private TextView tvCode;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//验证码控件
tvCode = (TextView) findViewById(R.id.tv_code_number);
//点击事件
tvCode.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//吐司
Toast.makeText(MainActivity.this, "短信验证码已发送,请注意查收!", Toast.LENGTH_SHORT).show();
//创建TimeCount 设置总时间和计时间隔
TimeCount time = new TimeCount(5000, 1000);
//开始计时
time.start();
}
});
}
/**
* 短信倒计时
*/
class TimeCount extends CountDownTimer {
/**
* @param millisInFuture 总时长
* @param countDownInterval 计时间隔
*/
public TimeCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
/**
* 计时完毕时触发
*/
@Override
public void onFinish() {
//给按钮重新设置文字
tvCode.setText("重新验证");
//让按钮可点击
tvCode.setClickable(true);
//更改按钮背景
tvCode.setBackgroundResource(R.drawable.find_code_shape);
//更改按钮文字颜色
tvCode.setTextColor(getResources().getColor(R.color.colorMain));
}
/**
* 计时过程中显示
*
* @param millisUntilFinished 计时事件
*/
@Override
public void onTick(long millisUntilFinished) {//计时过程显示
//让按钮不可点击
tvCode.setClickable(false);
//设置按钮文字
tvCode.setText("重新发送" + millisUntilFinished / 1000 + "(s)");
//设置按钮背景
tvCode.setBackgroundResource(R.drawable.find_button_shape);
//设置按钮文字颜色
tvCode.setTextColor(getResources().getColor(R.color.color646464));
}
}
}
验证码倒计时视频: height="498" width="510" src="http://player.youku.com/player.php/sid/XMjUxODA3MzYyNA==/v.swf">