Create Clickable Hyperlinks in TextView in Android with Kotlin
Last Updated :
30 Jan, 2022
TextView is used to display text in Android. text can be characters, numbers, strings, and paragraphs. We can also display web URLs in the TextView. However, these links are non-clickable and cannot be used for website navigation. Moreover, we cannot create hyperlinks directly into the TextView.
So in this article, we will show you a correct way of creating hyperlinks in TextView that are clickable and navigable in Android. 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. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.
Step 2: Create a hyperlink in the strings.xml file
Go to res > values > strings.xml and add the following code.
XML
< resources >
< string name = "app_name" >GFG | TextViewHyperlinks</ string >
</ resources >
|
Step 3: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Add a TextView to display the Hyperlink.
XML
<? xml version = "1.0" encoding = "utf-8" ?>
< RelativeLayout
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity" >
< TextView
android:id = "@+id/text_view_1"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_centerInParent = "true"
android:text = "@string/hyperlink" />
</ RelativeLayout >
|
Step 4: 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 org.geeksforgeeks.textviewhyperlinks
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.method.LinkMovementMethod
import android.widget.TextView
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super .onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val mTextView = findViewById<TextView>(R.id.text_view_1)
mTextView.movementMethod = LinkMovementMethod.getInstance()
}
}
|
Output:
You can see that the string is underlined and on click opens the web page. (Keep the device connected to the internet)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...