Android linkify URLs links non URLs
I want to make web links inside a textview clickable. I used this code
tv.setLinksClickable(true);
tv.setAutoLinkMask(Linkify.WEB_URLS);
Linkify.addLinks(tv, Linkify.WEB_URLS);
which does linkify the web site URLs but also seems to randomly link other text like z.xyz dzo.yzw and others.
How can I tell the linkify to only link URLs? To try and detect links starting with http:// or https:// beginnings I tried this pattern compiling
tv.setLinksClickable(true);
Pattern httpPattern = Pattern.compile("^(http|https)://");
Linkify.addLinks(tv, httpPattern,"");
but that did not work (no links were highlighted). Is that RegEx correct? What should the 3rd parameter to addLinks be?
Thanks for any tips to get this working.
After much searching and trial and error, this is the solution. Do not use the default Linkiny.WEB_URLS. Use a custom regex pattern that looks for links. I used the following (et is an EditText).
et.setLinksClickable(true);
Pattern httpPattern = Pattern.compile("[a-z]+://[^ n]*");
Linkify.addLinks(et, httpPattern,"");
That will only linkify URLs and not other strings with 2 words separated by a full stop as Linkify.WEB_URLS can do.
If that regex is not good enough for your needs see the following link for heaps of tested alternatives that handle more complex cases https://mathiasbynens.be/demo/url-regex
Hope that helps someone else with the same issue.
Here'a s pattern that corresponds to RFC 3986 (URL standard):
public static final Pattern URL_PATTERN = Pattern.compile(
"(?:^|[W])((ht|f)tp(s?)://|www.)"
+ "(([w-]+.){1,}?([w-.~]+/?)*"
+ "[p{Alnum}.,%_=?&#-+()[]*$~@!:/{};']*)",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
from: https://stackoverflow.com/a/5713866/2980992.
You may go on this way:
String regex = "^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
if (tv.getText().toString().matches(regex)) {
tv.setLinksClickable(true);
Linkify.addLinks(tv, Linkify.WEB_URLS);
}
More about URL regex: Regular expression to match URLs in Java
链接地址: http://www.djcxy.com/p/74642.html上一篇: Android Linkify不会让电话号码可点击
下一篇: Android链接网址链接非网址