我要實現的功能是點擊按鈕開始工作,計時器開始計時,再點停止計時,再點一次接著之前的時間計時。我使用的是Chronometer 控件。
先看布局
<LinearLayout android:layout_width="match_parent" android:layout_height="70dp" android:gravity="center|bottom" android:orientation="horizontal" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="在線時長" android:textColor="#fff" android:textSize="32sp" /> <Chronometer android:id="@+id/timer" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="15dp" android:textColor="#fff" android:textSize="32sp" android:format="00:00:00"/></LinearLayout>定義一個總時間,秒為單位
PRivate int totalTime = 0;開始計時,調用Chronometer的監聽事件
timer.start();timer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() { @Override public void onChronometerTick(Chronometer chronometer) { totalTime++; timer.setText(FormatTime(totalTime)); }});規范時間的顯示格式
public static String FormatTime(int time) { String hh = time / 3600 > 9 ? time / 3600 + "" : "0" + time / 3600; String mm = (time % 3600) / 60 > 9 ? (time % 3600) / 60 + "" : "0" + (time % 3600) / 60; String ss = (time % 3600) % 60 > 9 ? (time % 3600) % 60 + "" : "0" + (time % 3600) % 60; return hh + ":" + mm + ":" + ss;}停止計時
timer.stop();我這里只是用到了開始和停止,如果想重置時間的話就設置它的base
timer.setBase(SystemClock.elapsedRealtime());因為我需要顯示時分秒,如果只是簡易的計時器,不需要“時”,則沒有必要調用監聽,代碼更簡單。只要初始化Chronometer后,給它設置格式規范,然后調用開始和停止的方法,就可以實現計時器功能。
timer.setFormat("%s");
新聞熱點
疑難解答