Creating a chronometer in Android Creating a chronometer in Android android android

Creating a chronometer in Android


Just implement the Chronometer in XML or Code and use its start() method to start it and its stop() method to stop it.

More can be found here: http://developer.android.com/reference/android/widget/Chronometer.html

XML:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <Chronometer        android:id="@+id/chronometer1"        android:layout_width="wrap_content"        android:layout_height="wrap_content" />    <Button        android:id="@+id/button1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Start"         android:onClick="startChronometer"/>    <Button        android:id="@+id/button2"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="Stop"         android:onClick="stopChronometer"/></LinearLayout>

Java:

public class Main extends FragmentActivity {    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.test);    }    public void startChronometer(View view) {        ((Chronometer) findViewById(R.id.chronometer1)).start();    }    public void stopChronometer(View view) {        ((Chronometer) findViewById(R.id.chronometer1)).stop();    }}

You might add some code to the startChronometer() method to restart the counter.