Url recognition in android textview, androidtextview
The url recognition in textview in android5.0 + may not be the desired result. For example, it recognizes 1. ### as a url. It may be intended to support baidu.com, leading to some unacceptable results.
There is no good way to handle it by yourself.
First, retrieve the url in the textview content:
Public List <String> getUrlsInContent (String content ){
List <String> termList = new ArrayList <String> ();
String patternString = "[http | https] + [: //] + [0-9A-Za-z:/[-] _ # [?] [=] [.] [&] [%] * ";
Pattern pattern = Pattern. compile (patternString );
Matcher matcher = pattern. matcher (content );
While (matcher. find ()){
TermList. add (matcher. group ());
}
For (String temp: termList ){
Log. I ("", temp );
}
Return termList;
}
Then process the strings in the content as hyperlinks:
TextView note_item_content = (TextView) parentView
. FindViewById (R. id. note_item_content );
String content = tempStruct. getContent ();
If (content. equals ("")){
ParentView. removeView (note_item_content );
} Else {
SpannableString ss = new SpannableString (content );
List <String> tempL = Utilities. getInstance (). getUrlsInContent (content );
If (tempL! = Null ){
For (String temp: tempL ){
Int index = content. indexOf (temp );
Ss. setSpan (new URLSpan (temp), index, index + temp. length (), Spanned. SPAN_EXCLUSIVE_EXCLUSIVE );
}
}
Note_item_content.setText (ss );
Note_item_content.setMovementMethod (LinkMovementMethod. getInstance ());
CharSequence text = note_item_content.getText ();
If (text instanceof Spannable ){
Int end = text. length ();
Spannable sp = (Spannable) note_item_content.getText ();
URLSpan [] urls = sp. getSpans (0, end, URLSpan. class );
SpannableStringBuilder style = new SpannableStringBuilder (text );
Style. clearSpans (); // shocould clear old spans
// Send the link cyclically
For (URLSpan url: urls ){
MyURLSpan myURLSpan = new MyURLSpan (url. getURL (), myHandler );
Style. setSpan (myURLSpan, sp. getSpanStart (url ),
Sp. getSpanEnd (url), Spannable. SPAN_EXCLUSIVE_INCLUSIVE );
}
Note_item_content.setText (style );
}
}
Here is a flaw: I only process the first matched url. If there are multiple identical URLs in the content, no special processing will be performed later.
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.