Skip to content

Instantly share code, notes, and snippets.

@JGeraldoLima
Last active February 8, 2025 01:57
Show Gist options
  • Save JGeraldoLima/fb6360e356517cd3880c96f76d394894 to your computer and use it in GitHub Desktop.
Save JGeraldoLima/fb6360e356517cd3880c96f76d394894 to your computer and use it in GitHub Desktop.
A JetpackCompose component to show pieces of a text as a hyperlink
package me.jgeraldo.compose.ui
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.LinkAnnotation
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.withLink
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.sp
@Composable
fun HyperLinkText(
modifier: Modifier? = Modifier,
text: String,
links: List<Pair<Int, String>>,
textStyle: TextStyle = TextStyle(
fontSize = 16.sp,
color = Color.Black,
fontWeight = FontWeight(500),
),
linkStyle: TextStyle = TextStyle(
fontSize = 16.sp,
color = HelpInstructionColor,
fontWeight = FontWeight(500),
textDecoration = TextDecoration.Underline
)
) {
val annotatedLinkString: AnnotatedString = remember {
buildAnnotatedString {
val words = text.split(" ")
for ((i, word) in words.withIndex()) {
val link = links.firstOrNull { it.first == i } // Check if the word is a link
if (link != null) {
withLink(LinkAnnotation.Url(url = link.second)) {
withStyle(style = linkStyle.toSpanStyle()) { append(word) }
}
} else {
withStyle(style = textStyle.toSpanStyle()) { append(word) }
}
// Add spaces except after the last word
if (i < words.size - 1) append(" ")
}
}
}
Text(annotatedLinkString, modifier!!)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment