5

I'm trying to add a link to a Twitter profile in an about box. 'Regular' links such as email address and web address are handled by

android:autoLink="email|web"

in about.xml, but for a Twitter profile page I need to use html code in my strings.xml. I've tried:

<string name="twitter">Follow us on &lt;a href=\"http://www.twitter.com/mytwitterprofile"&gt;Twitter: @mytwitterprofile&lt;/a&gt;</string>

which renders html markup on the about box.

I've also tried:

<string name="twitter">Follow us on <a href="http://www.twitter.com/mytwitterprofile">Twitter: @mytwitterprofile</a></string>

which display the text "Follow us on Twitter: @mytwitterprofile", but it is not a hyper-link.

How do I do this seemingly simple task!?

Cheers, Barry

barry
  • 4,037
  • 6
  • 41
  • 68
  • how do you add the string to your box? – Rajath Apr 22 '11 at 12:52
  • TextView textView = (TextView) findViewById(R.id.about_content); textView.setTextColor(Color.WHITE); textView.setText(getString(R.string.about_text, getString(R.string.twitter), getString(R.string.email_address), getString(R.string.website))); – barry Apr 22 '11 at 16:01
  • See if you find this post useful - http://stackoverflow.com/questions/1997328/android-clickable-hyperlinks-in-alertdialog – Rajath Apr 22 '11 at 12:56

3 Answers3

10

The problem is your "a href" link tags are within strings.xml and being parsed as tags when strings.xml is parsed, which you don't want. Meaning you need to have it ignore the tags using XML's CDATA:

<string name="sampleText">Sample text <![CDATA[<a href="www.google.com">link1</a>]]></string>

And then you can continue with Html.fromHtml() and make it clickable with LinkMovementMethod:

TextView tv = (TextView) findViewById(R.id.textHolder);
tv.setText(Html.fromHtml(getString(R.string.sampleText)));
tv.setMovementMethod(LinkMovementMethod.getInstance());
dule
  • 17,798
  • 4
  • 39
  • 38
5

The simple answer is that the TextView does not support <a> tags. AFAIK, it only supports basic formatting such as <b>, <i> and <u>. However, if you supply android:autoLink="web", the following string:

<string name="twitter">Follow us at twitter.com/mytwitterprofile</string>

Will turn twitter.com/mytwitterprofile into a proper link (when set via XML like android:text="@string/twitter"; if you want to set it from code, you'll need the Html.fromHtml method someone else posted in an answer).

Felix
  • 88,392
  • 43
  • 149
  • 167
  • Thanks for that. It's not perfect but it'll do. Incidentally, I didn't need the Html.fromHtml either (my about.xml has android:autoLink="email|web" though) – barry Apr 22 '11 at 13:13
2

I'm not too sure how to link using 'strings', but you could set text of the EditText or TextView using fromHtml...

TextView text = (TextView) findViewById(R.id.text);
text.setText(Html.fromHtml("<a href=\"http://www.google.com\">Google Link!</a>"));
text.setMovementMethod(LinkMovementMethod.getInstance());
Tom O
  • 1,780
  • 2
  • 20
  • 43