android: html in textview with link clickable [duplicate]

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

Leave a Comment