android: html in textview with link clickable [duplicate]
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?
Solution 1:
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:
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).