button获取验证码 点击倒计时

Posted wangyaqian1212

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了button获取验证码 点击倒计时相关的知识,希望对你有一定的参考价值。

自定义button

package com.bw.text.logindemo;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.widget.Button;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by wangyaqian on 2016/9/20.
 */
public class TimeButton extends Button

    private long lenght = 60 * 1000;// 倒计时长度,默认60    private String textafter = "s后重新获取";
    private String textbefore = "获取验证码";

    private Timer t;
    private TimerTask tt;
    private long time;

    public TimeButton(Context context) 
        super(context);
    

    public TimeButton(Context context, AttributeSet attrs) 
        super(context, attrs);
    

    public void start() 
        initTimer();
        this.setText(time / 1000 + textafter);
        this.setEnabled(false);
        t.schedule(tt, 0, 1000);
    

    private Handler handler = new Handler() 
        @Override
        public void handleMessage(Message msg) 
            super.handleMessage(msg);
            TimeButton.this.setText(time / 1000 + textafter);
            time -= 1000;
            if (time < 0) 
                TimeButton.this.setEnabled(true);
                TimeButton.this.setText(textbefore);
                clearTimer();
            
        
    ;

    private void clearTimer() 
        if (tt != null) 
            tt.cancel();
            tt = null;
        
        if (t != null) 
            t.cancel();
            t = null;
        
    

    private void initTimer() 
        time = lenght;
        t = new Timer();
        tt = new TimerTask() 
            @Override
            public void run() 
                handler.sendEmptyMessage(0x01);
            
        ;
    

    /**
     * 设置计时时候显示的文本
     */
    public TimeButton setTextAfter(String after)
    
        this.textafter = after;
        return this;
    

    /**
     * 设置点击之前的文本
     */
    public TimeButton setTextBefore(String before)
    
        this.textbefore = before;
        this.setText(textbefore);
        return this;
    

    /**
     * 设置到计时长度
     * @param lenght 时间 默认毫秒
     * @return
     */
    public TimeButton setLenght(long lenght)
    
        this.lenght = lenght;
        return this;
    



测试类:

public class OtherActivity extends AppCompatActivity 

    private TimeButton btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_other);
        btn = (TimeButton) findViewById(R.id.btn);
        btn.setTextBefore("获取验证码").setTextAfter("s后重新获取").setLenght(60 * 1000);
    

    public void startDian(View view)
        btn.start();
    


以上是关于button获取验证码 点击倒计时的主要内容,如果未能解决你的问题,请参考以下文章

iOS 短信验证码倒计时按钮的实现

MAC AxureRP9登录获取验证码倒计时

iOS 短信验证码倒计时按钮的实现

js实现验证码倒计时效果

JS实现验证码倒计时效果

获取验证码,倒计时防止button上的字闪烁