效果图:
布局:activity_main
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DaoJiShiActivity">
<TextView
android:id="@+id/tv_getCode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="获取验证码"/>
</RelativeLayout>
代码:MainActivity
public class MainActivityextends AppCompatActivity {
private TextView tv_getCode;
private TimeCount time;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 查找控件
tv_getCode = (TextView) findViewById(R.id.tv_getCode);
// 创建CountDownTimer对象
time = new TimeCount(10000, 1000);
// 点击事件
tv_getCode.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
time.start();// 开始计时
}
});
}
/**
* 定义一个倒计时的内部类
*/
class TimeCount extends CountDownTimer {
// 参数1:为总时长 参数2:计时的时间间隔
public TimeCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
// 计时完毕时触发
@Override
public void onFinish() {
tv_getCode.setText("重新验证");
tv_getCode.setClickable(true);
}
// 计时过程显示
@Override
public void onTick(long millisUntilFinished) {
tv_getCode.setClickable(false);
tv_getCode.setText(millisUntilFinished / 1000 + "秒");
}
}
}