标签:技术分享 blog fill oncreate androi ret term 计时 图片
现在好多个APP里面都有验证码倒计时按钮,实现方式大概有下面几种:
这篇主要就是说下用第三种方式实现,简单好用
以下是核心代码:
/**
* Created by hfs on 2017/5/9.
*/
public class TimeCount extends CountDownTimer {
private Button button;
private String tickText;
private String finishText;
/**
* @param millisInFuture 倒计时总时长
* @param countDownInterval 倒计时单位 毫秒.
*/
public TimeCount(long millisInFuture, long countDownInterval,
Button button,String tickText,String finishText) {
super(millisInFuture, countDownInterval);
this.button = button;
this.tickText=tickText;
this.finishText=finishText;
}
@Override
public void onTick(long millisUntilFinished) {
button.setText(millisUntilFinished / 1000 + tickText);
button.setEnabled(false);
}
@Override
public void onFinish() {
button.setEnabled(true);
button.setText(finishText);
}
}
我自己又简单的封装成了一个自定义的Button,以后直接用着个自定义的Button即可
/**
* Created by hfs on 2017/5/9.
*/
public class CountDownButton extends Button {
private TimeCount mTimeCount;
private long millisInFuture = 60000;
private long countDownInterval = 1000;
private String mTickText = "s后重新获取";
private String mFinishText = "重新获取";
public CountDownButton(Context context) {
super(context);
init(context);
}
public CountDownButton(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public CountDownButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
}
/**
* 设置倒计时多少毫秒结束
* 默认60秒
*
* @param millisInFuture 毫秒
*/
public void setMillisInFuture(long millisInFuture) {
this.millisInFuture = millisInFuture;
}
/**
* 设置倒计时间隔
* 默认1秒
*
* @param countDownInterval 倒计时间隔
*/
public void setCountDownInterval(long countDownInterval) {
this.countDownInterval = countDownInterval;
}
/**
* 设置倒计时过程中button显示内容
* @param text 默认 s后重新获取
*/
public void setOnTickText(String text) {
this.mTickText=text;
}
/**
* 设置倒计时结束button显示内容
* @param finishText 默认 重新获取
*/
public void setOnFinishText(String finishText){
this.mFinishText=finishText;
}
public void startCount() {
mTimeCount = new TimeCount(millisInFuture, countDownInterval, this, mTickText, mFinishText);
mTimeCount.start();
}
}
使用方法很简单,就几行代码即可:
public class MainActivity extends AppCompatActivity {
private CountDownButton mCountDownButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCountDownButton = (CountDownButton) findViewById(R.id.btn_count_down);
mCountDownButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mCountDownButton.startCount();
}
});
}
}
标签:技术分享 blog fill oncreate androi ret term 计时 图片
原文地址:http://www.cnblogs.com/wz901881/p/6838905.html