自定义的倒计时按钮应该很多人都做过,我想最常见的实现方式应该就是开启一个子线程,然后通过Handler去更新UI实现,
这里我自定义了一个按钮,通过在handler中发送handler的方式,也同样实现了计时器的效果,而且也不需要开子线程,是代码的内存消耗更小更具有操作性
实现效果如下
直接上代码:
package com.fizzer.doraemon.localdemo.Animation.View;import android.content.Context;import android.os.Handler;import android.os.Message;import android.util.AttributeSet;import android.widget.Button;import android.widget.Chronometer;/*** Created by Fizzer on /12/13.* Email: doraemonmqq@* 倒计时控件*/public class CountDownButton extends Button {private boolean isRunning = false;private int startTime = 10;private int changeTime;private int TASK_RUNNING = 1;public CountDownButton(Context context) {super(context);}public CountDownButton(Context context, AttributeSet attrs) {super(context, attrs);}public CountDownButton(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);}public void start() {isRunning = true;changeTime = startTime;setText(changeTime + "秒");updateRunning();}public void stop() {isRunning = false;updateRunning();}/*** 设置倒计时时间* @param time time*/public void setStartTime(int time) {this.startTime = time;}private void updateRunning() {if (isRunning) {mHandler.sendMessageDelayed(Message.obtain(mHandler, TASK_RUNNING), 1000);} else {mHandler.removeMessages(TASK_RUNNING);}}Handler mHandler = new Handler() {@Overridepublic void handleMessage(Message msg) {changeTime--;setText(changeTime + "秒");setClickable(false);if (changeTime >= 0) {mHandler.sendMessageDelayed(Message.obtain(mHandler, TASK_RUNNING), 1000);} else {changeTime = startTime;mHandler.removeMessages(TASK_RUNNING);setText("重新开始");setClickable(true);}}};/*** 界面关闭的时候,停止发送handler*/@Overrideprotected void onDetachedFromWindow() {super.onDetachedFromWindow();isRunning = false;updateRunning();}}
在使用的类中调用一下start方法就行了
mMyButton.start();