本文實(shí)例為大家分享了Android自定義倒計(jì)時(shí)按鈕的具體代碼,供大家參考,具體內(nèi)容如下
效果


代碼:
package com.dylan.frame.ui;import android.content.Context;import android.os.Handler;import android.os.Message;import android.util.AttributeSet;import android.view.View;import android.widget.Button;import java.util.Timer;import java.util.TimerTask;/** * 自定義倒計(jì)時(shí)按鈕 * <p/> * * @author Dylan * <p/> * [佛祖保佑 永無BUG] * Created by Dylan on 2015/11/5 0005. */public class CountdownButton extends Button implements View.OnClickListener { private long lenght = 60 * 1000;//默認(rèn)倒計(jì)時(shí)時(shí)間; private long time;//倒計(jì)時(shí)時(shí)長 private Timer timer;//開始執(zhí)行倒計(jì)時(shí) private TimerTask timerTask;//每次倒計(jì)時(shí)執(zhí)行的任務(wù) private String beforeText = "點(diǎn)擊獲取驗(yàn)證碼"; private String afterText = "秒后重新獲取"; private OnClickListener onClickListener;//按鈕點(diǎn)擊事件 /** * 更新顯示的文本 */ private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); CountdownButton.this.setText(time / 1000 + afterText); time -= 1000; if (time < 0) { CountdownButton.this.setEnabled(true); CountdownButton.this.setText(beforeText); clearTimer(); } } }; public CountdownButton(Context context) { super(context); this.setText(beforeText); setOnClickListener(this); } public CountdownButton(Context context, AttributeSet attrs) { super(context, attrs); setOnClickListener(this); } public CountdownButton(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); setOnClickListener(this); } /** * 清除倒計(jì)時(shí) */ private void clearTimer() { if (timerTask != null) { timerTask.cancel(); timerTask = null; } if (timer != null) { timer.cancel(); timer = null; } } /** * 設(shè)置倒計(jì)時(shí)時(shí)長 * * @param lenght 默認(rèn)毫秒 */ public void setLenght(long lenght) { this.lenght = lenght; } /** * 設(shè)置未點(diǎn)擊時(shí)顯示的文字 * * @param beforeText */ public void setBeforeText(String beforeText) { this.beforeText = beforeText; } /** * 設(shè)置未點(diǎn)擊后顯示的文字 * * @param beforeText */ public void setAfterText(String afterText) { this.afterText = afterText; } /** * 點(diǎn)擊按鈕后的操作 * * @param v */ @Override public void onClick(View v) { if (onClickListener != null) { onClickListener.onClick(v); } initTimer(); this.setText(time / 1000 + afterText); this.setEnabled(false); timer.schedule(timerTask, 0, 1000); } /** * 初始化時(shí)間 */ private void initTimer() { time = lenght; timer = new Timer(); timerTask = new TimerTask() { @Override public void run() { handler.sendEmptyMessage(1); } }; } /** * 設(shè)置監(jiān)聽按鈕點(diǎn)擊事件 * * @param onclickListener */ @Override public void setOnClickListener(OnClickListener onclickListener) { if (onclickListener instanceof CountdownButton) { super.setOnClickListener(onclickListener); } else { this.onClickListener = onclickListener; } }}以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選