Android应用增加计时器
昨天写的Sudoku游戏需要增加计时器功能,使用Chronometer实现如下,由于Chronometer自己在调用stop之后后台的计时器还会继续增加,所以暂停功能需要额外实现:
在StartActivity onCreate方法中添加如下代码:
textView = (TextView) findViewById(R.id.time_text); timer = (Chronometer) findViewById(R.id.chronometer); timer.setBase(SystemClock.elapsedRealtime()+timeWhenStopped); timer.start(); pauseButton = (Button) findViewById(R.id.pause); pauseButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { pauseOrStart++; if (pauseOrStart % 2 == 1) { Toast.makeText(StartActivity.this, "Pause", Toast.LENGTH_SHORT).show(); timeWhenStopped = timer.getBase() - SystemClock.elapsedRealtime(); timer.stop(); } else { Toast.makeText(StartActivity.this, "Start", Toast.LENGTH_SHORT).show(); timer.setBase(SystemClock.elapsedRealtime()+timeWhenStopped); timer.start(); } } });
在activity_start.xml中增加如下内容:
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingTop="5dp" android:orientation="horizontal"> <TextView android:id="@+id/time_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Time:" android:textSize="30sp" android:textColor="@color/green" android:layout_weight="2"/> <Chronometer android:id ="@+id/chronometer" android:layout_width="wrap_content" android:layout_height="wrap_content" android:format="%s" android:textSize="30sp" android:textColor="@color/green" android:layout_weight="25"/> <Button android:id="@+id/pause" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Pause" android:textColor="@color/green" android:background="@drawable/shape2" android:layout_weight="1"/> </LinearLayout>
带有pause功能的Chronometer的实现可以参考这里:
http://stackoverflow.com/questions/5594877/android-chronometer-pause
class PausableChronometer extends Chronometer { private long timeWhenStopped = 0; public PausableChronometer(Context context) { super(context); } public PausableChronometer(Context context, AttributeSet attrs) { super(context, attrs); } public PausableChronometer(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public void start() { setBase(SystemClock.elapsedRealtime()+timeWhenStopped); super.start(); } @Override public void stop() { super.stop(); timeWhenStopped = getBase() - SystemClock.elapsedRealtime(); } public void reset() { stop(); setBase(SystemClock.elapsedRealtime()); timeWhenStopped = 0; } public long getCurrentTime() { return timeWhenStopped; } public void setCurrentTime(long time) { timeWhenStopped = time; setBase(SystemClock.elapsedRealtime()+timeWhenStopped); } }
-------------------------------
问道,修仙
-------------------------------