在安卓開發過程中經常需要計數器的使用,我們可以用handler實現間隔性的操作。
例如按兩次返回back退出,隔幾秒重複換頁面等。
但是也經常有一類需求類是打電話時候記錄時長的操作。
這就用到了android中 android.widget包下的Chronometer 這個組件。
轉載請註明:http://blog.csdn.net/xuanguofeng/article/details/45579037 謝謝
Chronometer介紹
Class that implements a simple timer.
* <p>
* You can give it a start time in the {@link SystemClock#elapsedRealtime} timebase,
* and it counts up from that, or if you don't give it a base time, it will use the
* time at which you call {@link #start}. By default it will display the current
* timer value in the form "MM:SS" or "H:MM:SS", or you can use {@link #setFormat}
* to format the timer value into an arbitrary string.
*
* @attr ref android.R.styleable#Chronometer_format
本人英語不好 ,就不在這獻醜了。抱歉。。。。。
首先先看佈局文件
三個按鈕和 一個Chronometer的控件 沒有特殊方法
Activity邏輯代碼部分
大部分方法都已經註釋
注意 chronometer.getText();方法返回的CharSequence這個對象,我們通過這個對象可以操作裏面的數據
CharSequence類裏面的方法有:
public int length();
public char charAt(int index);
public CharSequence subSequence(int start, int end);
public String toString();
這四個方法看名字也知道啥意思第一個獲取長度、第二根據位置獲取字符、第三個截取、第四個toString
我們可以根據獲取到的屬性進行不同的操作,例如:到5秒的時候進行操作可以
if("00:05".equals(text.toString())){
要進行的操作;
}
也可以獲取字符
if( text.charAt(text.length()-1)==5){
要進行的操作;
}
還可以自己拆分字符串進行操作總之各種方法就不獻醜了。
這就是一個簡單計時器在android開發中的使用。