这个例子演示的是点击按钮之后,计数增长,到20后自动停止
其中main.xml代码为:
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:layout_width="fill_parent" 4 android:layout_height="fill_parent" 5 android:orientation="vertical" > 6 7 <Chronometer 8 android:id="@+id/chronometer1" 9 android:layout_width="wrap_content" 10 android:layout_height="wrap_content" 11 android:text="Chronometer" /> 12 13 <Button 14 android:id="@+id/button1" 15 android:layout_width="wrap_content" 16 android:layout_height="wrap_content" 17 android:text="Start" /> 18 19 </LinearLayout>
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 }
==============================================================================
本文转自被遗忘的博客园博客,原文链接:http://www.cnblogs.com/rollenholt/archive/2012/05/17/2506054.html,如需转载请自行联系原作者