xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:orientation="vertical" > <Chronometer android:id="@+id/chronometer" android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button_1" android:text="@string/start"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button_2" android:text="@string/stop"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button_3" android:text="@string/reset"/> </LinearLayout>
java中
package com.will.chronometer; import android.app.Activity; import android.os.Bundle; import android.os.SystemClock; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Chronometer; import android.widget.Chronometer.OnChronometerTickListener; public class MainActivity extends Activity implements OnClickListener { Chronometer chronometer = null; Button but1 = null; Button but2 = null; Button but3 = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); chronometer = (Chronometer)findViewById(R.id.chronometer); but1 = (Button)findViewById(R.id.button_1); but2 = (Button)findViewById(R.id.button_2); but3 = (Button)findViewById(R.id.button_3); but1.setOnClickListener(this); but2.setOnClickListener(this); but3.setOnClickListener(this); // chronometer.setFormat("现在时间是: %s"); chronometer.setOnChronometerTickListener(new OnChronometerTickListener() { @Override public void onChronometerTick(Chronometer chronometer) { if(SystemClock.elapsedRealtime() - chronometer.getBase() > 5000) chronometer.stop(); } }); } @Override public void onClick(View v) { switch(v.getId()) { case R.id.button_1: chronometer.setBase(SystemClock.elapsedRealtime()); chronometer.start(); break; case R.id.button_2: chronometer.stop(); break; case R.id.button_3: chronometer.setBase(SystemClock.elapsedRealtime()); break; default: break; } } }