In Android, a TextView is a user interface control used to set and display the text to the user.
We could use a TextView to create a hyperlink that loads a web page in a mobile web browser when clicked. In fact, this is often seen in websites when we click on an image or text.
In this article, you will be learning how to create hyperlinks with android text views, like the one in the image above.
Step 1: Navigate to the
strings.xml
file.
<string name="hyperlink"><a href="https://twitter.com/tech_queen">Follow me on Twitter</a></string>
href
: holds the link
<a> </a>
: holds the text we would like to see on screen
Step 2: Add a text view on your layout.
<TextView
android:id="@+id/link"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="28dp"
android:text="@string/hyperlink"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button"
app:layout_constraintVertical_bias="0.0" />
android:text
: holds the hyperlink
string resource file we created
Step 3: Connect the dots in the MainActivity.kt file.
//Kotlin
private fun setupHyperlink() {
val linkText = findViewById<TextView>(R.id.link)
linkText.movementMethod = LinkMovementMethod.getInstance()
linkTextView1.setLinkTextColor(Color.BLUE)
}
//Java
private void setupHyperlink() {
TextView linkTextView = findViewById(R.id.activity_main_link);
linkTextView.setMovementMethod(LinkMovementMethod.getInstance());
}
By clicking on the text, your Android application will automatically redirect you to the webpage.