Andorid中实现验证码功能时候控件倒计时的多种实例

来源:互联网 发布:淘宝拒签退款有风险吗 编辑:程序博客网 时间:2024/06/05 06:04

实现倒计时功能的两种方法1.使用handler机制,通过handler传递消息,然后在UI线程中更新UI,自定义Handler,继承于父类Handler,重写其HandleMessage();2.自定义Timer,继承与父类CountDownTimer,重写里面的Onfinish()和OnTick()方法,给你的自定义Timer提供自己的实现;

package com.yqq.activitytest;import android.os.CountDownTimer;import android.widget.Button;/** * 自定义Timer * Created by user on 2016/12/23. */public class TimeCount extends CountDownTimer{    private Button button;    public TimeCount(long millisInFuture, long countDownInterval) {        super(millisInFuture, countDownInterval);    }    public TimeCount(Button bt,long millisInFuture, long countDownInterval) {        super(millisInFuture, countDownInterval);        this.button = bt;    }    @Override    public void onTick(long l) {        String time = "(" + l/1000 + ")秒";        setButtonInfo(time,false);    }    @Override    public void onFinish() {        setButtonInfo("重新获取",true);    }    private void setButtonInfo(String content,boolean isClick){        button.setText(content);        button.setClickable(isClick);    }}
在Activity中通过如下代码调用
new TimeCount(test2,10000,1000).start();


2.使用handler的机制动态更新UI

自定义Handler

package com.yqq.activitytest;import android.app.Activity;import android.os.Handler;import android.os.Message;import android.widget.Button;/** * Created by user on 2016/12/23. */public class MyHandler extends Handler{    private  Activity context;    private Button button;    public MyHandler(Activity activity,Button bt){        this.context = activity;        this.button = bt;    }    @Override    public void handleMessage(Message msg) {        super.handleMessage(msg);            switch (msg.what){                case 0:                    if (msg.arg1 == 0){                        button.setText("重新获取");                        button.setClickable(true);                    }else {                        button.setText("(" + (msg.arg1) + ")秒");                        button.setClickable(false);                    }                    break;            }    }}

在Activity中需要调用倒计时的控件使用此方法

private void sendMessage(){        final com.yqq.activitytest.MyHandler handler = new com.yqq.activitytest.MyHandler(A.this,test3);        new Thread(new Runnable() {            @Override            public void run() {                for (int i = 10; i >=0; i--) {                    Message msg = handler.obtainMessage();                    msg.arg1 = i;                    msg.what = 0;                    handler.sendMessage(msg);                    try{                        Thread.sleep(1000);//使线程每隔1s休眠                    }catch (InterruptedException e){                        e.printStackTrace();                    }                }            }        }).start();    }

模拟器的运行效果



0 0
原创粉丝点击