1. 程式人生 > >Android 自定義獲取驗證碼倒計時按鈕

Android 自定義獲取驗證碼倒計時按鈕

 

 

import android.content.Context;
import android.os.CountDownTimer;
import android.support.v7.widget.AppCompatButton;
import android.util.AttributeSet;

/**
 * Created by Administrator on 2017/5/25.
 * 倒時間button
 *
 * 倒計時提示:
 * setHintText()
 * 開始計時
 * onStart()
 * 結束計時
 * onCancel()
 *請務必在activity或fragment的onDestroy()方法裡執行onCancel()方法
 * 其他方法和button一樣,包括設定背景色和文字顏色等
 * 
 *
 *  使用方法:
 *  CountDownButton timerButton = findViewById(R.id.TimerButton);
 * timerButton.setHintText("%d秒後重新獲取"); //不設定的話,預設為“xx秒後重新獲取”
 * timerButton.setCountdownTime(60); //不設定預設為60秒
 * timerButton.setText("獲取驗證碼");
 * timerButton.setOnClickListener(new View.OnClickListener() {
 * @Override
 * public void onClick(View v) {
 * //開始倒計時
 * timerButton.onStart();
 * }
 * });
 *
 * 在activity或fragment的onDestroy()方法裡執行onCancel()方法
 *  protected void onDestroy() {
 *     super.onDestroy();
 *     timerButton.onCancel();
 *  }
 *
 */

public class CountDownButton extends AppCompatButton {

    private String text;
    private String hint = "%d秒後重新獲取";
    private int second = 60;
    private CountDownTimer timer;
    private String baseText = "";

    public CountDownButton(Context context) {
        this(context,null);
    }

    public CountDownButton(Context context, AttributeSet attrs) {
        this(context, attrs, R.attr.buttonStyle);
    }

    public CountDownButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        baseText = getText().toString();
    }

    private void setHintCount(int i){
        String text = String.format(hint,i);
        setText(text);
    }

    public void setHintText(String hint){
        //hint格式為內容+%d,如:“%d秒後重新獲取”
        this.hint = hint;
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        this.text = text.toString();
        super.setText(text, type);
    }

    public void setCountdownTime(int second) {
        this.second = second;
    }


    public void onStart(){
        baseText = getText().toString();
        if(timer == null){
            timer = getCountDownTimer(second);
        }
        timer.cancel();
        timer.start();
    }

    private CountDownTimer getCountDownTimer(int time){
        return new CountDownTimer(time*1000,1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                if(isClickable())
                setClickable(false);
                setHintCount((int)millisUntilFinished/1000);
            }

            @Override
            public void onFinish() {
                setClickable(true);
                setText(baseText);
            }
        };
    }

    public void onCancel(){
        if(timer != null){
            timer.cancel();
        }
    }


}