Android Chronometer can be used to display a simple timer. It can be given a start time (considered 00:00) from which it counts up. The base time can be set by using SystemClock.elapsedRealtime() method.
Step 1: Create a new project with name ChronometerExample and package name com.myexample.chronometer. Select File/New/New Project. Fill the forms and click “Finish” button.
Step 2: Open res/layout/xml (or) main.xml and add following code. Here we will create a Chronometer and a Button in a LinearLayout.
<?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:gravity="center" android:padding="10dp" android:orientation="vertical"> <Chronometer android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="50sp" android:textColor="#FB1F11" android:id="@+id/mainChronometer1"/> <Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="START" android:id="@+id/mainButton1"/> </LinearLayout>
Step 3: Open app/src/main/java/package and open MainActivity.java. Add following code in it. Here when the Button is clicked, we will start the Chronometer. When clicked again we will stop the Chronometer. And when clicked third time we will reset the Chronometer.
package com.myexample.chronometer; import android.app.*; import android.os.*; import android.widget.*; import android.view.*; public class MainActivity extends Activity { private Chronometer stopclock; private Button button1; private int BASE = 0; private int RUNNING = 1; private int STOPPED = 2; private int mode = BASE; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); stopclock = findViewById(R.id.mainChronometer1); button1 = findViewById(R.id.mainButton1); button1.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ if (mode == BASE){ stopclock.setBase(SystemClock.elapsedRealtime()); stopclock.start(); mode = RUNNING; button1.setText("STOP"); } else if (mode == RUNNING){ stopclock.stop(); mode = STOPPED; button1.setText("RESET"); } else if (mode == STOPPED){ mode = BASE; stopclock.setText("00:00"); button1.setText("START"); } } }); } }
Output:
Now run the app. When you click the Button it will start the Chronometer. When clicked again it will stop the Chronometer. And when clicked while Chronometer is stopped, it will reset the Chronometer.