Kotlin 倒计时

这篇博客介绍了如何在Kotlin中实现倒计时功能,包括设置布局、使用Handler进行消息处理以及如何启动和发送倒计时操作。通过示例代码展示了具体的实现步骤和最终效果。

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

Kotlin 倒计时

布局

  <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"
                  android:layout_marginTop="15dp" android:orientation="horizontal"
    >
        <EditText android:layout_width="match_parent" android:layout_height="wrap_content"
                  android:layout_weight="1" android:hint="请输入手机号"
                  android:layout_marginLeft="15sp"
                  android:id="@+id/et_user_phone"
        />
        <Button android:layout_width="wrap_content" android:layout_height="wrap_content"
                android:text="获取验证码"  android:background="#2196F3"
                android:textColor="#FFF" android:textSize="15sp"
                android:layout_marginRight="15sp"
                android:id="@+id/send_message"

        />
    </LinearLayout>
    <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"
                  android:layout_marginTop="15dp" android:orientation="horizontal"
    >
        <EditText android:layout_width="100dp" android:layout_height="wrap_content"
                  android:hint="验证码"
                  android:layout_marginLeft="15sp"
                  android:id="@+id/et_user_code"
        />

    </LinearLayout>

Handler

internal var mHandler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when(msg.what){
                100 -> send_message.text= "剩余时间(${time})秒"
                200 -> {
                    send_message.isEnabled=true
                    send_message.text = "点击重发"
                    time=60
                }
            }
        }
    }

发送

send_message.isEnabled= false
 Thread(cutTask()).start()
 var time=60
    inner class cutTask(): Runnable {
        override fun run() {
            while (time>0){
                mHandler.sendEmptyMessage(100)
                SystemClock.sleep(999)
                time--
            }
            mHandler.sendEmptyMessage(200)
        }

    }

效果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值