界面设计视图
<RelativeLayout 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" >
<AnalogClock
android:id="@+id/analogClock1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="63dp"
android:layout_marginTop="19dp" />
<Chronometer
android:id="@+id/chronometer1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/analogClock1"
android:layout_centerHorizontal="true"
android:layout_marginTop="37dp"
android:text="Chronometer" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/analogClock1"
android:layout_below="@+id/chronometer1"
android:layout_marginTop="46dp"
android:text="开始" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/button1"
android:layout_alignBottom="@+id/button1"
android:layout_marginLeft="26dp"
android:layout_toRightOf="@+id/chronometer1"
android:text="结束" />
</RelativeLayout>
处理程序的代码
package com.hbsi.csdn.timer;
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 TimerActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Chronometer ch=(Chronometer) findViewById(R.id.chronometer1);
Button btn1=(Button) findViewById(R.id.button1);
btn1.setOnClickListener(new OnClickListener(
) {
public void onClick(View v) {
// TODO Auto-generated method stub
ch.setBase(SystemClock.elapsedRealtime());
ch.start();
}
});
/*Button btn2=(Button) findViewById(R.id.button2);
btn2.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
ch.stop();
}
});*/
ch.setOnChronometerTickListener(new OnChronometerTickListener(){
public void onChronometerTick(Chronometer arg0) {
if(SystemClock.elapsedRealtime()-ch.getBase()>10*1000){
ch.stop();
}
}
});
}
}