App中经常会用到倒计时,Android本身提供了CountDownTimer类来方便开发者。
先上效果图:
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.anyanyan.vmoive.R;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class Main4Activity extends AppCompatActivity {
@BindView(R.id.et_phoneNum)
EditText mEtPhoneNum;
@BindView(R.id.tv_getCode)
TextView mTvGetCode;
private CountDownTimer mCountDownTimer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);
ButterKnife.bind(this);
//第一个参数60000表示总时间,第二个参数1000表示间隔时间,即每隔1000ms会调用一次onTick方法
mCountDownTimer = new CountDownTimer(60000,1000) {
/**
* @param millisUntilFinished:距离完成剩余的毫秒数
*/
@Override
public void onTick(long millisUntilFinished) {
mTvGetCode.setText("重新发送"+millisUntilFinished/1000+"s");
}
/**
* 倒计时完成时回调
*/
@Override
public void onFinish() {
//倒计时完成后设置回文字,并可点击
mTvGetCode.setText("获取验证码");
mTvGetCode.setClickable(true);
}
};
}
@OnClick(R.id.tv_getCode)
public void getCode() {
String phoneNum = mEtPhoneNum.getText().toString();
if (TextUtils.isEmpty(phoneNum)){
Toast.makeText(this,"请输入手机号",Toast.LENGTH_SHORT).show();
return;
}
//倒计时开始
mCountDownTimer.start();
//设置不可点击
mTvGetCode.setClickable(false);
}
}
当然,为了使用方便,我们对其进行封装
package com.anyanyan.vmoive.customView;
import android.os.CountDownTimer;
import android.widget.TextView;
/**
* Created by Administrator on 2016/12/7.
*/
public class MyCountDownTimer extends CountDownTimer {
private String getCode, sendAgainText;
private TextView mTextView;
public MyCountDownTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
public MyCountDownTimer(TextView textView, String getCode, String sendAgainText) {
super(60000, 1000);
this.getCode = getCode;
this.mTextView = textView;
this.sendAgainText = sendAgainText;
}
@Override
public void onTick(long millisUntilFinished) {
mTextView.setText(sendAgainText + millisUntilFinished / 1000 + "s");
}
@Override
public void onFinish() {
mTextView.setText(getCode);
mTextView.setClickable(true);
}
}
然后:
MyCountDownTimer mCountDownTimer = new MyCountDownTimer(mTvGetCode,"获取验证码","重新发送");
mCountDownTimer.start();
mTvGetCode.setClickable(false);
就调用成功了。