4

I used this (not so nice anymore) example to enable linkification on my Android Jetpack Compose Text composable (see section with "The ClickableText handles link on text").

That works so far easy and nice for one language. As you can see in the AnnotatedString.Builder:

addStyle(
    style = SpanStyle(
        textDecoration = TextDecoration.Underline
    ),
    start = 8,
    end = 15
)
addStringAnnotation(
    tag = uriTag,
    annotation = "https://developer.android.com/jetpack/compose",
    start = 8,
    end = 15
)

I have to enter start and end indices to highlight the link by underlines. Imagine I have multiple string language resources and I only want to linkify website or Webseite:

 "My website" 
 "Meine Webseite"

The upper english string would have start and end indices from 4 to 10.

Lower german string would have 7 to 14. This is for multiple language resources not very usable. How can I linkify my Text composable more easily, without calculating indices.

(Please note: I want to use natural libraries andoridx.* kotlin.* only. Other 3rd party libraries will be ignored)

Ralf Wickum
  • 2,850
  • 9
  • 55
  • 103
  • Your approach is not generalized. You need to split the string by space take the last element in the array and resolve the indexes, then apply the span. – Nikola Despotoski Jun 14 '22 at 15:06
  • Hope this is still relevant. There are a few ways you can work this around. You can create a helper function to get the start and end indices of your texts. You can also checkout `AndroidView`. These links should help: https://gist.github.com/micHar/99d8da443bfb9fc2e92a61ebaaacba72 https://stackoverflow.com/a/72369830/8649647 https://stackoverflow.com/a/65656351/8649647 – Damilola Omoyiwola Aug 24 '22 at 14:17

1 Answers1

0

You can use offset like below.

onClick = { offset ->
                        annotatedText.getStringAnnotations(start = offset, end = offset)
                            .firstOrNull()?.let {
                                onLinkClick(it.item)
                            }
                    }
 
Sriraksha
  • 459
  • 1
  • 8
  • 15