How to change text style when user presses on subtext in ClickableText in jetpack compose

75 views Asked by At

I am implementing screen which shown terms and conditions text something like.

By continuing you are agreeing to our terms of service.      

When user clicks on terms of service sub string I am opening web page with actual terms of service.

I am using ClickableText with string annotations as mentioned here

For better user experience I want to highlight terms of service text when user press on it. When user clicks terms of service its fine to directly navigate but when user only presses the terms of service I want to highlight terms of service so that user will know terms of service is being clicked.

Ideally I want something like selector drawable which changes background of button when pressed.

<!-- pressed -->
<item android:drawable="@drawable/button_1_selected" android:state_pressed="true"/>
<!-- default -->
<item android:drawable="@drawable/button_1_normal"/>

Can someone help me figure out how can we add selector kind of effect on terms of service subtext.

1

There are 1 answers

0
BenjyTec On

You haven't provided any code, but from my perspective, you can simply create two annotated Strings. One annotated String represents the normal look, the other one represents the clicked state. For the second one, you define that the terms of service is highlighted in some way.

val normalString = buildAnnotatedString {
    // ...
}

val highlightedString = buildAnnotatedString {
    append("By continuing, you are agreeing to the ")
    withStyle(style = SpanStyle(background = Color.Yellow)) {
        append("Terms and Services")
    }
    append(".")
}

Then, you create a variable that holds the annotated String and assign it to your ClickableText Composable:

var currentString by remember { mutableStateOf(normalString) }
ClickableText(text = currentString, onClick = { /** **/ })

At handling the click onto the text, just switch the annotated Strings:

currentString = highlightedString