您的位置:首页 > 移动开发 > Android开发

Android倒计时控件

2015-12-04 10:00 573 查看
项目有一个倒计时特卖的需求

具体代码如下

import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;

public class TimerTextView extends TextView implements Runnable{

public TimerTextView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}

private long mday, mhour, mmin, msecond;//天,小时,分钟,秒
private boolean run=false; //是否启动了

public void setTimes(long[] times) {
mday = times[0];
mhour = times[1];
mmin = times[2];
msecond = times[3];

}

/**
* 倒计时计算
*/
private void ComputeTime() {
msecond--;
if (msecond < 0) {
mmin--;
msecond = 59;
if (mmin < 0) {
mmin = 59;
mhour--;
if (mhour < 0) {
// 倒计时结束,一天有24个小时
mhour = 23;
mday--;

}
}

}

}

public boolean isRun() {
return run;
}

public void beginRun() {
this.run = true;
run();
}

public void stopRun(){
this.run = false;
}

@Override
public void run() {
//标示已经启动
if(run){
ComputeTime();

String strTime= mday +"天:"+ mhour+"小时:"+ mmin+"分钟:"+msecond+"秒";
this.setText(strTime);

postDelayed(this, 1000);
}else {
removeCallbacks(this);
}
}

}


使用也很简单

long[] times = {0,shi,fen,miao}; //参数分别是 天 时 分 秒
holderView.tv_countdowntimer.setTimes(times);
if(!holderView.tv_countdowntimer.isRun()){
holderView.tv_countdowntimer.beginRun();
}


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