Android常用代码-发送验证码倒计时

  1. 1. 使用RxJava优雅的实现
  2. 2. 布局示例

使用RxJava优雅的实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
btnVerifyCode.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
btnVerifyCode.setEnabled(false);
Observable.interval(0, 1, TimeUnit.SECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(AndroidSchedulers.mainThread())
.limit(31)
.map(new Func1<Long, Long>() {
@Override
public Long call(Long aLong) {
return 30 - aLong;
}
})
.doOnSubscribe(new Action0() {
@Override
public void call() {
btnVerifyCode.setEnabled(false);
}
})
.doOnCompleted(new Action0() {
@Override
public void call() {
btnVerifyCode.setEnabled(true);
btnVerifyCode.setText("重新发送");
}
})
.subscribe(new Action1<Long>() {
@Override
public void call(Long aLong) {
btnVerifyCode.setText("重新发送("+aLong + " s )");
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
ToastUtils.showCustomBgToast("获取失败,错误信息:" + throwable.getMessage() + "");
}
});
}
});

布局示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<FrameLayout
android:id="@+id/ll_verify_code"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="70px"
android:orientation="horizontal">

<EditText
android:id="@+id/et_verify_Code"
android:layout_width="match_parent"
android:layout_height="108px"
android:background="@drawable/et_bg_line"
android:hint="@string/et_hint_code"
android:paddingLeft="100px"
android:paddingRight="280px"
android:textColor="@color/colorBlack"
android:textColorHint="#999"
android:textSize="36px" />

<ImageView
android:layout_width="50px"
android:layout_height="50px"
android:layout_gravity="center_vertical"
android:layout_marginLeft="20px"
android:src="@drawable/verification"
app:layout_auto_baseheight="width" />

<ImageView
android:id="@+id/iv_clear_verify_code"
android:layout_width="40px"
android:layout_height="40px"
android:layout_gravity="right|center_vertical"
android:layout_marginRight="320px"
android:src="@drawable/undo"
android:visibility="gone" />

<Button
android:id="@+id/btn_verify_code"
android:layout_width="wrap_content"
android:layout_height="78px"
style="?borderlessButtonStyle"
android:layout_gravity="center_vertical|right"
android:background="@drawable/full_round_shape_white_with_gray_border"
android:gravity="center"
android:paddingLeft="30px"
android:paddingRight="30px"
android:text="@string/get_code"
android:textColor="@color/btn_code_color_selector"
android:textSize="30px" />

</FrameLayout>