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

Asked

Viewed 78 times

1

Hello, I wonder if it is possible to define the initial value of a chonometer based on a textView.

TextView em destaque

texView who would like to set the beginning of Chronometer in blue highlight.

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

1 answer

0


The value in Textview is a string that represents minutes and seconds.
To use it, as the starting value of 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 format mm:ss. mm may be greater than 59.

Use later 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);
  • Works perfectly!! Thank you!!

  • Is it possible for Chronometer to exceed 60 minutes? As the textView is a time of a football match, it goes up to 90 minutes, but the Chronometer when it passes 60 he "Zera".

  • No, directly. If 60 minutes pass he will show 1:00:00. Indirectly you can use an Onchronometerticklistener and in the method onChronometerTick() take the current value of the text and change it to the format you want.

  • I changed the conversion method to allow values greater than 59 minutes.

  • @Lázarorodrigues, has the answer solved your question? Do you think you can accept it or do you need something else?

  • Yes, thank you very much!! There is only one problem, the timer "starts" when the screen item disappears through the recyclerview scroll, there is a way not to do that?

  • There is, but for that you need to see the code. Ask another question.

  • Code of Adapter or recyclerview?

  • I can’t be sure but the Adapter code should be sufficient.

Show 4 more comments

Browser other questions tagged

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