Search code examples
androidstringandroid-studioandroid-jetpack-compose

How to make one word in a string clickable on Android Jetpack Compsoe?


Until recently, I had always used XML's to create my screens, and I knew how to make certain TextViews clickable with those XML's.

Now, I'm transitioning to exclusively use Jetpack Compose, and no longer depend on XML.

What I'm currently trying to do is have one part of a text have a keyword that (if clicked) will let you go to another screen on the app.

For example, if my text says "Click here to go to the second screen", then when you click on "here" it should take you to the other screen. I looked at resources online for Compose, which have suggested using ClickableText, but this makes the whole sentence clickable while just making "here" a different color, which is not what I want.

For compose, what would be the best way for me to have a Text which can have the sentence above but only have one word ("here") clickable and do the click acion?


Solution

  • You can achieve above thing by buildAnnotatedString. Define your text here and pass in clickable text

        @Composable
        fun SpannableTextScreen() {
        
            val text = buildAnnotatedString {
                append("Click ")
                pushStringAnnotation(tag = "click", annotation = "click")
                withStyle(
                    SpanStyle(
                        textDecoration = TextDecoration.Underline,
                        color = Color.Red
                    )
                ) {
                    append("here ")
                }
                pop()
                append("to go to the second screen")
            }
            val context = LocalContext.current
        
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(horizontal = 20.dp),
                contentAlignment = Alignment.Center
            ) {
                ClickableText(text = text, onClick = { offset ->
                    text.getStringAnnotations(tag = "click", start = offset, end = offset).firstOrNull()
                        ?.let {
                            // on click operation here
                            Toast.makeText(context, "hey", Toast.LENGTH_SHORT).show()
                        }
                })
            }
        
        }
    

    only here text is clickable , Now when you click on here a toast will show , you can modify according to your requirement

    enter image description here