2011年4月15日星期五

簡單的 Android 計時器(Chronometer)

android.widget.Chronometer 是一個實現簡單計時器的類.

範例:
Android 計時器(Chronometer)

package com.SimpleTimer;

import android.app.Activity;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;

public class SimpleTimer extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Button Start = (Button)findViewById(R.id.start);
Button Stop = (Button)findViewById(R.id.stop);
Button Reset = (Button)findViewById(R.id.reset);
final Chronometer timer = (Chronometer)findViewById(R.id.timer);

Start.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
timer.start();
}});

Stop.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
timer.stop();
}});

Reset.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
timer.setBase(SystemClock.elapsedRealtime());
}});

}
}


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:id="@+id/start"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Start"
/>
<Button
android:id="@+id/stop"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Stop"
/>
<Button
android:id="@+id/reset"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Reset"
/>
<Chronometer
android:id="@+id/timer"
android:layout_gravity="center_horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>

沒有留言:

發佈留言