Chronometer display value greater than 60 minutes in MM:SS format

Asked

Viewed 73 times

1

Hello, there is the possibility of a Chronometer displaying more than 60 minutes without entering the hour format?

My Chronometer receives data from a String to set the starting value.

private long minutesAndSecondsToMilliseconds(String minutesAndSeconds){
    String[] timeParts = minutesAndSeconds.split(":");
    int minutes = Integer.parseInt(timeParts[0]);
    int seconds = Integer.parseInt(timeParts[1]);
    return (minutes * 60 + seconds) * 1000;
}

However on receiving 80:00 minutes for example, Chronometer displays 1:20:00. There is the possibility display the 80:00?

1 answer

1


By default the value is displayed in the "MM:SS" format, passing to the "H:MM:SS" format when the minute is greater than 59.

The class Chronometer provides the method serFormat() however, contrary to what your name may suggest, it does not serve to alter this pattern.
It is used to compose a string, to be presented, in which a first occurrence of "%s" is replaced by the current value of the stopwatch, in the form "MM:SS" or "H:MM:SS".

For example, use chronometer.setFormat("Passaram %s desde o início"); will result in

  • if the value is less than 60 seconds:

    Passaram 48:55 desde o início

  • if the value is greater than 59 seconds:

    Passaram 1:25:23 desde o início

If there is no method in the class that does this directly, it is possible to do so indirectly using a OnChronometerTickListener and in the method onChronometerTick() take the current value, format it as you like and assign it to the Chronometer text.

chronometer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
    @Override
    public void onChronometerTick(Chronometer chronometer) {
        long time = SystemClock.elapsedRealtime() - chronometer.getBase();
        String minSec = String.format("%02d:%02d",
                TimeUnit.MILLISECONDS.toMinutes(time),
                TimeUnit.MILLISECONDS.toSeconds(time) -
                        TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time))
        );
        chronometer.setText(minSec);
    }
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.