83

I use an a-htmltag in my TextView, but when i tap on it nothing happens.

How can I make it open the web browser with the url?

Macarse
  • 91,829
  • 44
  • 175
  • 230
clamp
  • 33,000
  • 75
  • 203
  • 299

2 Answers2

233

Try this

txtTest.setText( Html.fromHtml("<a href=\"http://www.google.com\">Google</a>"));
txtTest.setMovementMethod(LinkMovementMethod.getInstance());

Remember : don't use android:autoLink="web" attribute with it. because it causes LinkMovementMethod doesn't work.

Update for SDK 24+ The function Html.fromHtml deprecated on Android N (SDK v24), so turn to use this method:

    String html = "<a href=\"http://www.google.com\">Google</a>";
    Spanned result = HtmlCompat.fromHtml(html,Html.FROM_HTML_MODE_LEGACY);
    txtTest.setText(result);
    txtTest.setMovementMethod(LinkMovementMethod.getInstance());

Here are the list of flags:

FROM_HTML_MODE_COMPACT = 63;
FROM_HTML_MODE_LEGACY = 0;
FROM_HTML_OPTION_USE_CSS_COLORS = 256;
FROM_HTML_SEPARATOR_LINE_BREAK_BLOCKQUOTE = 32;
FROM_HTML_SEPARATOR_LINE_BREAK_DIV = 16;
FROM_HTML_SEPARATOR_LINE_BREAK_HEADING = 2;
FROM_HTML_SEPARATOR_LINE_BREAK_LIST = 8;
FROM_HTML_SEPARATOR_LINE_BREAK_LIST_ITEM = 4;
FROM_HTML_SEPARATOR_LINE_BREAK_PARAGRAPH = 1;

Update 2 with android.text.util.Linkify, it's more easier now to make a clickable TextView:

TextView textView =...
Linkify.addLinks(textView, Linkify.WEB_URLS);
Axbor Axrorov
  • 2,720
  • 2
  • 17
  • 35
Nguyen Minh Binh
  • 23,891
  • 30
  • 115
  • 165
16

You can do it this way;

mTextView = (TextView) findViewById(R.id.textView);
String text = "Visit my developer.android.com";
mTextView.setText(text);
// pattern we want to match and turn into a clickable link
Pattern pattern = Pattern.compile("developer.android.com");
// prefix our pattern with http://
Linkify.addLinks(mTextView, pattern, "http://")
Mudassir
  • 13,031
  • 8
  • 59
  • 87