您的位置:首页 > 其它

安卓开发之显示倒计时按钮控件

2016-08-05 22:49 288 查看
实现倒计时逻辑比较简单,使用了CountDownTimer来计时(源码考虑了线程安全问题)。

对使用逻辑封装成了一个自定义控件TimerButton。

源代码:

import android.content.Context;
import android.os.CountDownTimer;
import android.util.AttributeSet;
import android.widget.Button;

/**
* Created by cxm on 2016/8/5.
*/
public class TimerButton extends Button {

private String beforeText ;
private String afterText = "重发";
private int ms = 10000;

public TimerButton(Context context) {
super(context);
}

public TimerButton(Context context, AttributeSet attrs) {
super(context, attrs);
}

public TimerButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}

public void init(String beforeText,String afterText,int ms){

this.beforeText = beforeText;
this.afterText = afterText;
this.ms = ms;
this.setText(beforeText);
}

public void startTimer(){

new CountDownTimer(ms,1000){

@Override
public void onTick(long finish) {
TimerButton.this.setEnabled(false);
TimerButton.this.setText(finish/1000+" s");
}

@Override
public void onFinish() {
TimerButton.this.setEnabled(true);
TimerButton.this.setText(afterText);
}
}.start();

}

}


使用:

private TimerButton timerButton;

timerButton = (TimerButton) findViewById(R.id.timer_Button);

timerButton.init("获取验证码","重发",10000);

timerButton.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View view) {

timerButton.startTimer();

//TODO YOURS

//Toast.makeText(MainActivity.this,"TODO",Toast.LENGTH_SHORT).show();

}

});


Github:github地址
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐