Kotlin: Listen to time changes in Chronometer


Topics interesting only for Kotlin / Android / SQLite programmers

Link to this posting

Postby Ursego » 15 Mar 2020, 07:04

@ If you want your Chronometer to be persistent (i.e. to keep counting after app restart), do these steps.

@ Add to the Activity, in which you want to listen to Chronometer ticking:

Code: Select all
import android.widget.Chronometer

@ Make that Activity implementing the Chronometer.OnChronometerTickListener interface, for example:

Code: Select all
class MainActivity : AppCompatActivity(), Chronometer.OnChronometerTickListener {

@ Add to the Activity an implementation of the onChronometerTick() function of that interface:

Code: Select all
    override fun onChronometerTick(chronometer: Chronometer?) {
        // Do whatever when the chronometer achieves some time:
        when (chronometer.text) {
            "30:00" -> {...} // "30:00:0" if the Chronometer displays tenths of seconds
            "45:00" -> {...}
            "01:00:00" -> {...}
        }
    }

@ Add to onCreate() of the Activity:

Code: Select all
myChronometer.onChronometerTickListener = this

IF YOU HAVE MORE THAN ONE CHRONOMETER:

@ In onCreate() of the Activity, register them all:

Code: Select all
firstChronometer.onChronometerTickListener = this
secondChronometer.onChronometerTickListener = this

@ Create function xxxxxxxChronometerTicked() for each Chronometer, for example:

Code: Select all
    private fun firstChronometerTicked() {
        // Do whatever when the chronometer achieves some time:
        when (firstChronometer.text) {
            "30:00" -> {...}
            "45:00" -> {...}
            "01:00:00" -> {...}
        }
    }

@ Call all these functions from onChronometerTick():

Code: Select all
    override fun onChronometerTick(chronometer: Chronometer?) {
        when (chronometer!!.id) {
            firstChronometer.id -> firstChronometerTicked()
            secondChronometer.id -> secondChronometerTicked()
        }
    }
User avatar
Ursego
Site Admin
 
Posts: 143
Joined: 19 Feb 2013, 20:33



Ketones are a more high-octane fuel for your brain than glucose. Become a biohacker and upgrade yourself to version 2.0!



cron
Traffic Counter

eXTReMe Tracker