Java代码:
package com.example.chronometer;
import android.app.Activity;import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.Chronometer.OnChronometerTickListener;
import android.os.Build;
import com.example.chronometer.R;
public class MainActivity extends Activity {
Chronometer ch;
Button start;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
ch=(Chronometer)findViewById(R.id.test);
start=(Button)findViewById(R.id.start);
start.setOnClickListener(new View.OnClickListener() {
public void onClick(View source)
{
ch.setBase(SystemClock.elapsedRealtime());
ch.start();
start.setEnabled(false);
}
});
ch.setOnChronometerTickListener(new OnChronometerTickListener()
{
public void onChronometerTick(Chronometer ch)
{
if(SystemClock.elapsedRealtime()-ch.getBase()>20*1000)
{
ch.stop();
start.setEnabled(true);
}
}
});
}
}
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"
android:orientation="vertical"
android:gravity="center_horizontal"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.chronometer.MainActivity$PlaceholderFragment" >
<Chronometer
android:id="@+id/test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24pt"
android:textColor="#99ff00"
/>
<Button
android:id="@+id/start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="启动"
android:textSize="24pt"
/>
</LinearLayout>