创建
/**
* @author weimian
* 自定义倒计时文本控件
*/
public class TimeTextView extends TextView implements Runnable{
//Paint mPaint; //画笔,包含了画几何图形、文本等的样式和颜色信息
private long[] times;
private long mday, mhour, mmin, msecond;//天,小时,分钟,秒
private boolean run=false; //是否启动了
public TimeTextView(Context context, AttributeSet attrs) {
super(context, attrs);
// mPaint=new Paint();
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.TimeTextView);
array.recycle(); //一定要调用,否则这次的设定会对下次的使用造成影响
}
public TimeTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// mPaint=new Paint();
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.TimeTextView);
array.recycle(); //一定要调用,否则这次的设定会对下次的使用造成影响
}
public TimeTextView(Context context) {
super(context);
}
public long[] getTimes() {
return times;
}
public long[] getNowTimes(){//取得现在剩下的倒计时
if(times!=null){
times[0] = this.mday;
times[1] = this.mhour;
times[2] = this.mmin;
times[3] = this.msecond;
}
return times;
}
public void setTimes(long[] times) {
this.times = 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) {
// 倒计时结束
mhour = 23;
mday--;
}
}
}
}
public boolean isRun() {
return run;
}
public void setRun(boolean run) {
this.run = run;
}
@Override
public void run() {
//标识已经启动
run=true;
ComputeTime();
String strTime="倒计时:"+mday+""+"天"+mhour+"时"+mmin+"分"+msecond+"";
if(mday<0){
strTime = "已经结束了";
removeCallbacks(this);
}
this.setText(strTime);
postDelayed(this, 1000);
}
}
/**
* 分割时间
* @param endTime
* @return
*/
public static long[] getLongArray(String endTime,String now){
long[] arrayTime = null;
if(endTime!=null && !endTime.isEmpty()){
long it = Long.parseLong(endTime);
long nw = (System.currentTimeMillis()/1000);//默认客户端时间
if(now!=null && !now.isEmpty()){//当前时间则使用服务器时间
nw = Long.parseLong(now);
}
long difference=it-nw;
try {
if(difference>0){
long day=difference/(60*60*24);
long hour=difference%(60*60*24)/(60*60);
long min=difference%(60*60*24)%(60*60)/60;
long second=difference%(60*60*24)%(60*60)%60;
arrayTime = new long[4];
arrayTime[0] = day;
arrayTime[1] = hour;
arrayTime[2] = min;
arrayTime[3] = second;
return arrayTime;
}
} catch (Exception e) {
return arrayTime;
}
return arrayTime;
}
return arrayTime;
}
使用方式
long time_end=System.currentTimeMillis()+10*1000;//结束时间 10秒
long nowtime=System.currentTimeMillis();//当前时间
timeView.setTimes(getLongArray(time_end,nowtime));
if(!timeView.isRun()){
timeView.run();
}
