这个例子演示的是点击按钮之后,计数增长,到20后自动停止
其中main.xml代码为:
java代码为:
1 package android.demo; 2 3 import android.app.Activity; 4 import android.os.Bundle; 5 import android.os.SystemClock; 6 import android.view.View; 7 import android.view.View.OnClickListener; 8 import android.widget.Button; 9 import android.widget.Chronometer; 10 import android.widget.Chronometer.OnChronometerTickListener; 11 12 public class AndroidDemo5Activity extends Activity { 13 /** Called when the activity is first created. */ 14 @Override 15 public void onCreate(Bundle savedInstanceState) { 16 super.onCreate(savedInstanceState); 17 setContentView(R.layout.main); 18 19 Button start = (Button) findViewById(R.id.button1); 20 final Chronometer ch = (Chronometer) findViewById(R.id.chronometer1); 21 22 start.setOnClickListener(new OnClickListener() { 23 24 @Override 25 public void onClick(View arg0) { 26 ch.setBase(SystemClock.elapsedRealtime()); 27 ch.start(); 28 } 29 }); 30 ch.setOnChronometerTickListener(new OnChronometerTickListener() { 31 32 @Override 33 public void onChronometerTick(Chronometer arg0) { 34 if (SystemClock.elapsedRealtime() - ch.getBase() > 20 * 1000) { 35 ch.stop(); 36 } 37 38 } 39 }); 40 } 41 }