Set start time of a Chonometer with the text of a textView

1

Hello, I would like to know if you can set the initial value of a chonometer based on a textView.

texView that would like to set the start of the highlighted blue chronometer.

This textView receives data from a server, but it is not real-time, updating only on OnResume.

    
asked by anonymous 26.08.2017 / 02:38

1 answer

0

The value that is in the TextView is a string that represents minutes and seconds. To use it as the start value of the Chonometer, you have to convert it to milliseconds.

Create a method for conversion:

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;
}

Note: The method assumes that the value in the string minutesAndSeconds is in the mm:ss format. mm can be greater than 59.

Use it like this:

TextView textView = (TextView)findViewById(R.id.textView); 
Chronometer chronometer = (Chronometer)findViewById(R.id.chronometer);
...
...
long milliseconds = minutesAndSecondsToMilliseconds(textView.getText().toString());
chronometer.setBase(SystemClock.elapsedRealtime() - milliseconds);
    
26.08.2017 / 17:06