CountDownTimer倒计时

效果图:
CountDownTimer倒计时_第1张图片

布局:activity_main




   


代码: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 + "秒");
        }
    }
}

你可能感兴趣的:(CountDownTimer倒计时)