How do you make a text clickable in jetpack compose ? I would also like to toggle it to non clickable after selecting once

Viewed 6108
        Text(
            text = "Resend OTP",
            fontSize = 20.sp,
            color =  Textfieldcolor,
            style = TextStyle(textDecoration = TextDecoration.Underline)
        )

//This is my code this text should be selectable once and then be disabled .

2 Answers

You can add the clickable modifier or can use the ClickableText:

var enabled by remember { mutableStateOf(true)}

ClickableText(
    text = AnnotatedString(text) ,
    onClick = {
        if (enabled) {
            enabled = false
            text = "Disabled"
        }
    })

Like @Arpit mentioned it would be better to use a TextBotton for this purpose. But if you absolutely want to use Text, You can use following snippet.

@Composable 
fun OneTimeClickableText(text : String, onClick : () -> Unit){
    var enabled by rememberSaveable{ mutableStateOf(true)}
    Text(
        modifier = Modifier
            .clickable(enabled = enabled) {
                enabled = false
                onClick()
            },
        text = text
    )
}

That said I this code is strictly for one-time clickable text. I won't recommend using it for something like OTP button; as user won't be able to click it unless they restart your app. You can pull the enabled variable and manage it from outside(e.g. keeping it disabled for certain amount of time rather than permanently).

Related