使用CountDownTimer达到倒计时效果(可做短信验证码倒计时)

项目中我们经常会用获取短信验证码之后的一个倒计时,今天给大家分享个用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">

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值