Opinions expressed are solely my own and do not express the views or opinions of my employer.

Saturday, December 22, 2012

Creating TextView with clickable links in Android

Did you ever want to display a TextView on Android which includes clickable HTML-links? I know I did. If you also wanted that, then I bet you struggled in finding a solution.

At first I thought, this can't be too hard, because I remember the TextView having a property linksClickable. But just setting this property to true won't work. Here are two methods how you can solve the problem described:

A) The almost-XML-only approach
If you want to work with XML-layouts only, you're out of luck. There's at least one line of code you have to write in your Java code-behind:
1. As usual, declare your TextView in XML and set the property android:linksClickable="true":
<TextView android:id="@+id/myTextView" android:linksClickable="true" text="@string/mylinks"/>

2. As a text, just refer to your @string-resource. Be careful to not use the CDATA in the resource. Just use the HTML anchor-tag(s):
<string name="mylinks">Please click <a href="http://android.com">here</a></string>

3. Finally, set the movementMethod in your code-behind file to the LinkMovementMethod's instance:

4. Do not, I repeat, do not set the android:autoLink. Otherwise the anchor-tag(s) will not be displayed correctly!

B) The more-or-less-Java approach
If you prefer Java and don't want to touch XML (which I wouldn't recommend), here's what to do:
1. Create your TextView in Java (or get a reference from your XML-layout ;) and set the linksClickable property to true:
TextView myTextView = new TextView(context);

2. Again, create the text as a @string-resource (using resources is my recommendation, not a must ;), but this time make sure that the content of the string resource is set as CDATA:

<string name="mylinks"><![CDATA[Please click <a href="http://android.com">here</a>]]></string>

3. Set the text using the Html helper class to make sure the TextView actually contains HTML and not just plaintext:

4. Now follow the steps 3 and 4 to make sure the links are actually clickable.

At the end I want to thank the StackExchange community that I was able to find a hint for the autoLink-problem and probably got inspired for the whole blog post ;)