Android进阶之路 - CountDownTimer倒计时的分秒实现

阅读与使用本文知识,仅需5分不到!

好吧,在此之前请原谅我吧,因为我竟然一直不知道有CountDownTimer这样的一个类能快速实现倒计时的功能

之前的话,我们可能在类中定义一个60秒的时间,之后在事件内部开启子线程进行倒计时处理(当然可以异步处理),然后在通过Handle刷新UI

现在的话,我们只需要使用CountDownTimer这个类就可以如标题一样分秒实现倒计时功能了

Ecfect:
这里写图片描述
MainActivity :

package com.example.dow.countdown;

import android.graphics.Color;
import android.os.CountDownTimer;
import android.support.annotation.ColorInt;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private TextView mBtn;
    private CountDownTimer timer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mBtn = (TextView) findViewById(R.id.tv_btn);
        //打开倒计时的同时,设置为不可点击
        mBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                view.setEnabled(false);
                timer.start();
            }
        });

        //首先创建CountDownTimer(倒计时)类,内部俩个回调,一个是正在进行时,另外一个就是倒计时结束的处理
        timer = new CountDownTimer(6000, 1000){

            @Override
            public void onTick(long millisUntilFinished) {
                mBtn.setText(millisUntilFinished/1000 + "秒");
                mBtn.setBackgroundColor(Color.rgb(60,63,65));
            }

            @Override
            public void onFinish() {
                mBtn.setEnabled(true);
                mBtn.setBackgroundColor(Color.rgb(0,118,216));
                mBtn.setText("获取验证码");
            }
        };
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        timer.cancel();
    }
}

MainActivity Xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.dow.countdown.MainActivity">

    <TextView
        android:layout_marginTop="20dp"
        android:layout_centerHorizontal="true"
        android:padding="10dp"
        android:id="@+id/tv_btn"
        android:textColor="#fff"
        android:background="#0076D8"
        android:layout_width="120dp"
        android:gravity="center"
        android:singleLine="true"
        android:layout_height="wrap_content"
        android:text="获取验证码" />
</RelativeLayout>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

远方那座山

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值