阅读与使用本文知识,仅需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>