【Android UI设计】之自定义计时器

来源:互联网 发布:ubuntu tm 编辑:程序博客网 时间:2024/06/12 23:16
本博文所分享项目已开源,大家可以在https://github.com/crazycodeboy/DigitalTimer上下载

DigitalTimer简介

  • 在样式上DigitalTimer支持自定义文字背景,大小,颜色的自定义。
  • 在功能上DigitalTimer支持启动计时,计时暂停等功能。

运行效果图

运行效果图数字计时器

XML Attributes

Attribute RelatedRelated MethodDescriptionapp:textColorsetBaseTime(long baseTime)设置基准时间app:textBgRessetTextBgRes(int textBgRes)设置文字背景app:textSizeetTextSize(float textSize)设置文字大小

使用方法

  1. java public void setBaseTime(long baseTime)设置基准时间
  2. java public void start()开始计时。
  3. java public void stop()停止计时。
  4. 其它使用细节可以参照实例。

实现原理

为了实现每一秒刷新一次计时时间,本博文中分别使用了CountDownTimer方式和Handler+Runnable的方式来刷新时间,使用CountDownTimer的方式:
countDownTimer=new CountDownTimer(999999999,1000) {@Overridepublic void onTick(long millisUntilFinished) {changTime=System.currentTimeMillis()-baseTime+1000;reSetTime();}@Overridepublic void onFinish() {}};
说明:这种方式利用了CountDownTimer类,该类会在指定的时间内回调onTick方法,从而实现计时的效果。
使用Handler+Runnable的方式:
private final Handler mHandler = new Handler();private final Runnable mTimeRefresher = new Runnable() {@Overridepublic void run() {changTime+=1000;reSetTime();mHandler.postDelayed(this, REFRESH_DELAY);}};

说明:这种方式定义了一个任务该,该任务会在指定的时间里回调run()方法来进行计时。





3 0