Home > Mobile >  how can I do text timer
how can I do text timer

Time:12-01

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
)

CodePudding user response:

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) {
        var second = 0
        while (second < 60) {
            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

  • Related