user1123530
user1123530

Reputation: 561

Creating a chronometer in Android

I'd like to know how can I implement in Android a simple chronometer with a start and stop button that displays data in the HH:MM:SS:MsMs format... I've been searching and searching and I have found some classes on google developer, but they didn't give examples and I got lost... Could you direct me to a tutorial/example? I'm just starting out in Android :) Any help would be much appreciated.

Upvotes: 13

Views: 35819

Answers (1)

user1014917
user1014917

Reputation: 681

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.

Upvotes: 17

Related Questions