需求:
登陆或者注册时点击获取验证码按钮,进行60s倒计时,倒计时过程中不允许点击按钮。倒计时秒数需要实时显示
效果图:
图1是未获取之前,图2是点击之后
思路:
倒计时一般有几种解决方案,常用用Timer,Handler,RxJava。
不过经过测试Timer和Handler时间都有误差,不准。项目建议采用RxJava
关键代码:
在项目的build.gradle中添加RxJava2依赖
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
implementation 'io.reactivex.rxjava2:rxjava:2.0.7'
注:如果项目已经有RxJava2就不用重复添加了
TimeUtils
public static Disposable dealCountDownS(long second, Consumer<Long> nextObserver, Consumer<Throwable> errorObserver, Action completeObserver ) {
return Observable
.interval(1, TimeUnit.SECONDS, AndroidSchedulers.mainThread())
.take(second)
.subscribe(nextObserver,errorObserver,completeObserver);
}
开始使用:
public class RegOneNewActivity extends BaseActivity<RegOneIView, RegOnePresenter> implements RegOneIView {
@BindView(R.id.tv_get_code)
TextView tvGetCode;
//是否开启倒计时
private boolean isStartCountDown;
private Disposable subscription;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initHeadView(R.layout.activity_regist_one_new, false);
showRealView();
}
@Override
protected void initPrClick() {
super.initPrClick();
//获取验证码
ViewShow.prClick(tvGetCode, new Action1() {
@Override
public void call(Object o) {
if (!isStartCountDown) {
onGetRegCode()
}
}
});
}
public void onGetRegCode() {
//获取验证码成功,进行倒计时
isStartCountDown = true;
//Constant.CODE_COUNTDOWN_TIME :60
tvGetCode.setText(Constant.CODE_COUNTDOWN_TIME + "s");
subscription = TimeUtils.dealCountDownS(Constant.CODE_COUNTDOWN_TIME, new Consumer<Long>() {
@Override
public void accept(Long aLong) throws Exception {
//每隔一秒
if (null != tvGetCode) {
tvGetCode.setText((TextUtils.concat(String.valueOf(Math.abs(aLong - Constant.CODE_COUNTDOWN_TIME)), "s")).toString());
}
}
}, new Consumer<Throwable>() {
//倒计时错误的回调
@Override
public void accept(Throwable throwable) throws Exception {
if (null != tvGetCode) {
tvGetCode.setText(mContext.getString(R.string.get_code));
}
isStartCountDown = false;
}
}, new Action() {
//倒计时完成的回调
@Override
public void run() throws Exception {
if (null != tvGetCode) {
tvGetCode.setText(R.string.get_code);
}
isStartCountDown = false;
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
if (subscription != null && !subscription.isDisposed()) {
subscription.dispose();
}
}
}