是否有一个很好的 Kotlin 示例如何将计时器值作为字符串传递给参数?

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

我在 Kotlin Android 应用程序片段中有一个可用的 Chronomer。当我单击暂停或停止按钮时,我希望能够将停止的计时器值传递给一个参数,然后在其他地方将其显示为 example:1m30s.

有什么提示可以在哪里查看?

解决方案

假设在你的片段中,chronometerChronomer 的变量名。当用户单击 pause/stop 按钮时,使用此代码获取计时器值。

// 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)
}