android: html in textview with link clickable

AndroidHtmlTextview

Android Problem Overview


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?

Android Solutions


Solution 1 - Android

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);

Solution 2 - Android

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://")

Hope, this helps. Please see this blog post for details. (Its not mine, and I am not associated with it in anyway. Posted here for information purpose only).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionclampView Question on Stackoverflow
Solution 1 - AndroidNguyen Minh BinhView Answer on Stackoverflow
Solution 2 - AndroidMudassirView Answer on Stackoverflow