先上非常直观的效果图:
主要是重写了Textview控件,废话不多说,直接贴代码!!
import android.content.Context; import android.content.res.TypedArray; import android.graphics.Paint; import android.util.AttributeSet; import android.widget.TextView; /** * 自定义倒计时文本控件 * @author Administrator * */ public class TimeTextView extends TextView implements Runnable{ Paint mPaint; //画笔,包含了画几何图形、文本等的样式和颜色信息 private long[] times; private long mday, mhour, mmin, msecond;//天,小时,分钟,秒 private boolean run=false; //是否启动了 private TimeChangeListener lister; public TimeTextView(Context context, AttributeSet attrs) { super(context, attrs); mPaint=new Paint(); TypedArray array = context.obtainStyledAttributes(attrs, android.support.v7.appcompat.R.styleable.ActionBar); array.recycle(); //一定要调用,否则这次的设定会对下次的使用造成影响 } public TimeTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mPaint=new Paint(); TypedArray array = context.obtainStyledAttributes(attrs, android.support.v7.appcompat.R.styleable.ActionBar); array.recycle(); //一定要调用,否则这次的设定会对下次的使用造成影响 } public TimeTextView(Context context) { super(context); } public long[] getTimes() { return times; } public void setLister(TimeChangeListener mylister) { this.lister = mylister; } public void cancleLister() { this.lister = null; } public void setTimes(long[] times) { this.times = times; mday = times[0]; mhour = times[1]; mmin = times[2]; msecond = times[3]; String strTime = ""; if(mhour<10) { strTime += "0"+mhour; } else { strTime += mhour; } strTime += ":"; if(mmin<10) { strTime += "0"+mmin; } else { strTime += mmin; } strTime += ":"; if(msecond<10) { strTime += "0"+msecond; } else { strTime += msecond; } this.setText(strTime); } /** * 增加计算 */ private void ComputeTime() { msecond++; if (msecond > 59) { mmin++; msecond = 0; if (mmin > 59) { mmin = 0; mhour++; } } } public boolean isRun() { return run; } public void setRun(boolean run) { this.run = run; } public void stop() { run = false; } @Override public void run() { //标示已经启动 if(run) { ComputeTime(); String strTime = ""; if(null != lister) { lister.onChagnge(mhour,mmin,msecond); } if(mhour<10) { strTime += "0"+mhour; } else { strTime += mhour; } strTime += ":"; if(mmin<10) { strTime += "0"+mmin; } else { strTime += mmin; } strTime += ":"; if(msecond<10) { if(msecond<0) { msecond = 0; } strTime += "0"+msecond; } else { strTime += msecond; } this.setText(strTime); postDelayed(this, 1000); } } }
还有个接口,一块贴出来,这样您可以拿来直接用,很贴心吧?!
/** * http请求回调接口 * @author tyf * @date 2012-3-12 * @time 上午10:41:08 */ public interface TimeChangeListener { /** * http请求成功的回调函数 * @param resp 请求得到的数据 */ public void onChagnge(long h, long m, long s); }