android 按钮倒计时读秒

    最近项目中有涉及到android倒计时读秒功能的实现,于是上网搜了一下,各种方式都有,但是感觉要么存在bug,要么有点复杂,于是在参考了一些他人的实现方式后,自己写了一个。
代码如下:

public class MainActivity extends Activity {

private TimeCount timeCount;

private Button btn;

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timeCount = new TimeCount(10000, 1000);
btn = (Button) findViewById(R.id.btn);

btn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
timeCount.start();
}

});
}

class TimeCount extends CountDownTimer {
public TimeCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}

public void onFinish() {
btn.setText("获取验证码");
btn.setBackgroundResource(R.drawable.obtain_btn_bg);//正常背景
btn.setClickable(true);
}

public void onTick(long millisUntilFinished) {
btn.setClickable(false);
btn.setBackgroundResource(R.drawable.obtain_reading);//倒计时时灰色背景

btn.setText(millisUntilFinished / 1000 + "s后重新获取");
}
}
}

你可能感兴趣的:(android)