androidkotlintimeargumentschronometer

Is there a good Kotlin example how to pass the chronometer value into an argument as string?


I have a working Chronomer in Kotlin Android app in a Fragment. When I click the pause or stop button I would like to be able to pass that stopped chronometer value into an argument, then display it elsewhere as example:1m30s.

Any tips where to look?


Solution

  • Solution

    Assume in your fragment, chronometer is variable name of Chronomer. When users click on pause/stop button, use this code to get the chronometer value.

    // Regex for HH:MM:SS or MM:SS
    val regex = "([0-1]?\\d|2[0-3])(?::([0-5]?\\d))?(?::([0-5]?\\d))?"
    
    val pattern = Pattern.compile(regex)
    val matcher = pattern.matcher(chronometer.text)
    if (matcher.find()) {
        val isHHMMSSFormat = matcher.groupCount() == 4
        val chronometerValue = if (isHHMMSSFormat) {
            val hour = matcher.group(1).toInt()
            val minute = matcher.group(2).toInt()
            val second = matcher.group(3).toInt()
            "${hour}h${minute}m${second}s"
        } else {
            val minute = matcher.group(1).toInt()
            val second = matcher.group(2).toInt()
            "${minute}m${second}s"
        }
    
        // TODO: Pass the `chronometerValue` into argument
        //  or anything you want here
        Log.i("Chronometer Value", chronometerValue)
    }