Add Hyperlink at a Particular Text Span in Android using Jetpack Compose
Last Updated :
29 Mar, 2022
In Android, a TextView is used to display text inside the activity on the screen. Similarly, in Jetpack Compose, a Text element is used to display text on the activity screen. By default, Text cannot create a hyperlink around the text, So, we create a hyperlink using Annonated String and display it using Clickable Text.
So in this article, we will show you how you could create a Hyperlink at a particular Text Span in Android using Jetpack Compose. Follow the below steps once the IDE is ready.
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. While choosing the template, select Empty Compose Activity. If you do not find this template, try upgrading the Android Studio to the latest version. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.
Step 2: Add INTERNET permission in the AndroidManifest.xml file
XML
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.geeksforgeeks.jctextspanhyperlink">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.JCTextSpanHyperlink">
<activity
android:name=".MainActivity"
android:exported="true"
android:label="@string/app_name"
android:theme="@style/Theme.JCTextSpanHyperlink">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Step 3: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
package com.geeksforgeeks.jctextspanhyperlink
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.text.ClickableText
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.tooling.preview.Preview
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
// Calling the composable function
// to display element and its contents
MainContent()
}
}
}
// Creating a composable
// function to display Top Bar
@Composable
fun MainContent() {
Scaffold(
topBar = { TopAppBar(title = { Text("GFG | Text Span Hyperlink", color = Color.White) }, backgroundColor = Color(0xff0f9d58)) },
content = { MyContent() }
)
}
// Creating a composable function
// to create a Clickable Text
// Calling this function as content
// in the above function
@Composable
fun MyContent(){
// Creating an annonated string
val mAnnotatedLinkString = buildAnnotatedString {
// creating a string to display in the Text
val mStr = "Click this link to go to web site"
// word and span to be hyperlinked
val mStartIndex = mStr.indexOf("link")
val mEndIndex = mStartIndex + 4
append(mStr)
addStyle(
style = SpanStyle(
color = Color.Blue,
textDecoration = TextDecoration.Underline
), start = mStartIndex, end = mEndIndex
)
// attach a string annotation that
// stores a URL to the text "link"
addStringAnnotation(
tag = "URL",
annotation = "https://www.geeksforgeeks.org",
start = mStartIndex,
end = mEndIndex
)
}
// UriHandler parse and opens URI inside
// AnnotatedString Item in Browse
val mUriHandler = LocalUriHandler.current
Column(Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
// ???? Clickable text returns position of text
// that is clicked in onClick callback
ClickableText(
text = mAnnotatedLinkString,
onClick = {
mAnnotatedLinkString
.getStringAnnotations("URL", it, it)
.firstOrNull()?.let { stringAnnotation ->
mUriHandler.openUri(stringAnnotation.item)
}
}
)
}
}
// For displaying preview in
// the Android Studio IDE emulator
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
MainContent()
}
Output:
You can see that the hyperlink is created on the text span displaying the word "link".
Similar Reads
How to Add Margin in Android using Jetpack Compose? In Android, Padding is used to offset the content of the view by a specific number of pixels from either direction, i.e., padding from left, right, top and bottom. Using Padding, we can create multiple borders to a view by applying a combination of multiple padding and border. Â So in this article,
2 min read
Implement Markdown Text in Android using Jetpack Compose Markdown is a third-party git library that can be used to identify particular types of regex (Regular Expressions) that specifies a search pattern in the text. For example, if you write a passage and mention a website and a telephone number in it, Markdown Text would detect these patterns and create
3 min read
Add an Input Filter to the TextField in Android using Jetpack Compose In Jetpack Compose, a TextField is a UI element that lets users type in text as an input. This input can then be stored and used for various desired functions. As TextField has no character restrictions, users can type in any character. However, there can be a system where the application would acce
3 min read
Material Design Text Input Field using Jetpack Compose in Android Jetpack Compose is a modern toolkit for building native Android UI. Jetpack Compose simplifies and accelerates UI development on Android with less code, powerful tools, and intuitive Kotlin APIs. Compose is built to support material design principles. Many of its UI elements implement material desig
3 min read
Text in Android using Jetpack Compose Jetpack Compose is a new toolkit provided by Google. This is useful for designing beautiful UI designs. Android Text is a simple view in Android which is used to display text inside our App. In this article, we will take a look at the implementation of Text in Android using Jetpack Compose. Importan
5 min read