具有倒计时功能的自定义按钮

本文介绍了一个实现倒计时功能的按钮组件,包括如何设置总显示时间和显示间隔,以及点击事件的处理逻辑。代码示例展示了如何通过设置参数来启动和停止倒计时,同时提供了一个自定义的点击事件接口来扩展功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<span style="color:#ff0000;">可以直接设置相关数据(总显示时间,显示间隔)</span>
</pre><pre name="code" class="java">
public class CountDownButton extends Button {


    private int count;
    private Button button;
    public clickEvent mClickEvent;
    private long millisInFuture;//总秒数
    private long countDownInterval;//间隔时间
    private Timer timer;
    private TimerTask timerTask;


    public CountDownButton(Context context) {
        super(context);
    }


    public CountDownButton(final Context context, AttributeSet attrs) {
        this(context, attrs, 0);
        button = this;
        this.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (count == (int) (millisInFuture / 1000)) {
                    start();
                    mClickEvent.buttonClick();
                }
            }
        });
    }


    public CountDownButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }




    /**
     * 点击事件需要加入的功能重构该函数即可
     */


    public interface clickEvent {
        public abstract void buttonClick();
    }




    public void setNumber(long millisInFuture1, long countDownInterval1) {
        millisInFuture = millisInFuture1;
        countDownInterval = countDownInterval1;
        count = (int) (millisInFuture1 / 1000);
    }




    private Runnable timeCount = new Runnable() {


        @Override
        public void run() {
            countTime();
        }
    };


    private void countTime() {
        count--;
        button.setText(count + "秒后重发");
        if (count <= 0) {
            button.setEnabled(true);
            button.setText("发送验证码");
            timerTask.cancel();
            timer.cancel();
            timer = null;
            timerTask = null;
        }
    }


    /**
     * 定时器开启方法
     */
    private void start() {
        timer = new Timer();
        timerTask = new TimerTask() {


            @Override
            public void run() {
                button.post(timeCount);
            }
        };
        timer.schedule(timerTask, 0, 1000);
    }


    /**
     * 定时器取消方法
     */
    public void cancel() {
        if (timer != null) {
            timerTask.cancel();
            timer.cancel();
            timer = null;
            timerTask = null;
        }
    }

}


</pre><pre name="code" class="java">
</pre><pre name="code" class="java">
写的不好的地方请见谅.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值