user1762507 user1762507 - 1 month ago 7
Android Question

How do you make a StopWatch in android using the chronometer?

I'm trying to make a stopwatch for android as part of a score board app the problem is I'm not sure how to use the

chronometer to start, stop, then resume
from the time it stopped at or reset to 0. The only problem is that I'm not sure how to use the
setBase()
and
getBase()
methods properly.

public class MainActivity extends Activity {

int homecount, awaycount, minutes, seconds;
TextView home, away;
Button stop, start, reset, addhome, subhome, addaway, subaway;
TextView time;
public boolean running;


Chronometer MyChronometer;
long startTime, stopTime;
running = false;
stopTime = 0;
MyChronometer = (Chronometer) findViewById(R.id.timer);

start.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
((Chronometer) findViewById(R.id.timer)).start();
startTime=System.currentTimeMillis();
running = true;
}
});

stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
((Chronometer) findViewById(R.id.timer)).stop();
stopTime=System.currentTimeMillis();
running = false;
}
});

reset.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {

}
});

Answer

You have the variable MyChronometer. Use that every time you want to start or stop.

Also, right after initialization you should run MyChronometer.setBase(SystemClock.elapsedRealtime());. For more details read the documentation: Chronometer and SystemClock.

Comments