简单实现获取验证码view
自定义TextView 内部自定义CountDownTimer实现倒计时
public class PassCodeTextView extends TextView {
private MyCountDownTimer myCountDownTimer;
public PassCodeTextView(Context context) {
super(context);
init();
}
public PassCodeTextView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public PassCodeTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
myCountDownTimer = new MyCountDownTimer(60000, 1000);
myCountDownTimer.setTextView(this);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
public void startCountDown() {
if (null != myCountDownTimer && getText().toString().contains("获取验证码")) {
myCountDownTimer.start();
}
}
class MyCountDownTimer extends CountDownTimer {
private TextView textView;
public MyCountDownTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
private void setTextView(TextView textView) {
this.textView = textView;
}
@Override
public void onTick(long millisUntilFinished) {
textView.setClickable(false);
textView.setText(millisUntilFinished / 1000 + "s");
}
@Override
public void onFinish() {
textView.setText("获取验证码");
textView.setClickable(true);
}
}
}
使用:
public class MainActivity extends AppCompatActivity {
private PassCodeTextView passCodeTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main9);
passCodeTextView = findViewById(R.id.passcode);
passCodeTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
passCodeTextView.startCountDown();
}
});
}
}