[Android] How to add clickable links to TextViews in Android
by Riley MacDonald, December 11, 2017

While working on a new release for my Intoxication Calculator Android Application I wanted to add a clickable attribution note for a graphic designer. She asked that I link her email and website in the application so she could add it to her portfolio. A quick search revealed I could just inject an html anchor tag into the string resource to accomplish this. The link appeared to be working but I was unable to click on it. It turns out there’s a few gotchas you need to do to accomplish this. The url won’t be clickable or won’t appear correctly if you don’t meet these requirements:

  • The xml layout must include an autolink property/value.
  • The body of the anchor tag must include the url

Example Implementation
Here’s an example of how I would include a clickable link to my website in an Android TextView:

1
2
3
<!-- strings.xml -->
<string name="website">Please visit my website: <a href="https://rileymacdonald.ca">https://rileymacdonald.ca</a>
<string name="email">Please email me at: <a href="mailto:riley_macdonald@hotmail.com">riley_macdonald@hotmail.com</a>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!-- layout.xml -->
<TextView
  android:id="@+id/website_textview"
  android:layout_width="match_parent"
  android:layout_height="wrap_content" 
  android:text="@string/website"
  android:autoLink="web"/>
 
<TextView
  android:id="@+id/email_textview"
  android:layout_width="match_parent"
  android:layout_height="wrap_content" 
  android:text="@string/email"
  android:autoLink="email"/>
Open the comment form

Leave a comment:

Comments will be reviewed before they are posted.

User Comments:

Isra on 2020-06-12 23:07:25 said:
Thanks for the post Riley! But, since it's quite an old entry, is there any actual way to accomplish this without including the url in the anchor tag body? I know there is the LinkMovementMethod option available but just wondering if there is a pure xml solution to this.