how can I do text timer

Issue

I want to show timer of 1 minute when user click on Re-send

enter image description here

enter image description here

Text(
   text = "Re-send",
   modifier = Modifier.clickable { },
   color = Color.Blue
)

Solution

For creating text with 2 colors you need annotatedString, for re-send to be clickable you need index of re-send and ClickableText

to create a timer you can use LaunchedEffect as in snippet below

@Composable
private fun ResendTextSample() {

    val str = "Did you not receive the email? "
    val length = str.length

    var isTimerActive by remember {
        mutableStateOf(false)
    }

    var time by remember { mutableStateOf("") }

    LaunchedEffect(key1 = isTimerActive) {
       if(isTimerActive){
           var second = 0
           while (second < 15) {
               time = if(second <10) "0:0$second" else "0:$second"
               delay(1000)
               second++
           }
           isTimerActive = false
       }
    }

    val annotatedLinkString = buildAnnotatedString {

        append(str)
        withStyle(
            SpanStyle(
                color = Color.Blue,
            )
        ) {
            if (!isTimerActive) {
                append("Re-send")
            } else {
                append(time)
            }
        }
        append("\nCheck your spam filter")

    }

    ClickableText(
        text = annotatedLinkString,
        style = TextStyle(fontSize = 20.sp),
        onClick = {
            if (!isTimerActive && it >= length && it <= length + 7) {
                isTimerActive = true
            }
        }
    )
}

Result. In demo i set max time to 15 seconds to show that resend is enabled.

enter image description here

Answered By – Thracian

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published