一、使用ValueAnimator实现了倒计时的动画效果
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/tv_hqyzm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="获取验证码"
android:textSize="20sp"
android:textStyle="bold"
android:textColor="#00BCD4"
android:layout_gravity="center"
android:layout_margin="30dp"
>
</TextView>
</LinearLayout>
二、当点击的时候有一个小bug,当它倒计时的时候我在点击又从新开始倒计时,这时设置了一个boolean 值,当为true的时候让它执行倒计时给它设置成false,再次点击就不会从新开始执行直到60秒结束,显示重新发送的时候可以从新执行。
package com.wd.wangzhuangyu;
import androidx.appcompat.app.AppCompatActivity;
import android.animation.ValueAnimator;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private TextView mTv_hqyzm;
private boolean alint = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取id控件
mTv_hqyzm= findViewById(R.id.tv_hqyzm);
//设置点击事件
mTv_hqyzm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (alint){
ValueAnimator animator = ValueAnimator.ofInt(60,0);
//设置时间
animator.setDuration(60000);
//均匀显示
animator.setInterpolator(new LinearInterpolator());
//监听
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
int value = (Integer) animation.getAnimatedValue();
mTv_hqyzm.setText(value +"s重新发送");
mTv_hqyzm.setTextColor(Color.GRAY);
if(value==0){
mTv_hqyzm.setText("重新发送");
mTv_hqyzm.setTextColor(Color.parseColor("#00BCD4"));
alint = true;
}
}
});
//开启线程
animator.start();
alint = false;
}else {
Toast.makeText(MainActivity.this, "稍后重试", Toast.LENGTH_SHORT).show();
}
}
});
}
}