Android Compose ripple on part of text

54 views Asked by At

I have a text where i need only part of it to be clickable. I made it with the below code.

    val firstPart = "This is a test of "
    val secondPart = "clickable part of text"

    val annotatedText = buildAnnotatedString {
      val clickableStyle = SpanStyle(color = Color.Blue)

      val noClickableStyle = SpanStyle(color = Color.Black)

      val clickableText = {
        val index = pushStringAnnotation(
          tag = "click",
          annotation = "clickable"
        )
        pushStyle(clickableStyle)
        append(secondPart)
        pop(index = index)
      }

      val noClickableText = {
        pushStyle(noClickableStyle)
        append(firstPart)
      }

      noClickableText()
      clickableText()
    }

    ClickableText(
      modifier = Modifier
        .clickable(
          enabled = true,
          interactionSource = remember { MutableInteractionSource() },
          indication = rememberRipple(bounded = true)
        ) {}
        .fillMaxWidth()
        .padding(top = 20.dp),
      text = annotatedText,
      style = MaterialTheme.typography.bodyMedium,
      onClick = { offset ->
        annotatedText.getStringAnnotations(
          tag = "click",
          start = offset,
          end = offset
        ).firstOrNull()?.let {
          Toast.makeText(
            this@MainActivity,
            "Clicked ${it.item}",
            Toast.LENGTH_SHORT
          ).show()
        }
          })

With this way only the last part of text is clickable just I want, but I am wondering if it is possible to add ripple on this part of my text. In order to be better for the user to see the interaction. I tried to use the modifier.clickable on ClickableText like this:

interactionSource = remember { MutableInteractionSource() },
indication = rememberRipple(bounded = true)

but without success. Any help is welcome.

0

There are 0 answers