android textview 中url識別,androidtextview

來源:互聯網
上載者:User

android textview 中url識別,androidtextview
android5.0+中對textview中的url識別可能不會是自己想要的結果。例如它會將1.###識別為url。可能它的本意是對baidu.com支援,導致一些我們不能接受的結果。
沒有好的辦法,只能自己處理了。
首先檢索出textview內容中的url:
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;
}


然後將內容中的這些字串處理為超連結:
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();// should clear old spans


// 迴圈把連結發過去
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);
}
}


這裡有個瑕疵:我只對首個匹配的url做了處理,如果內容裡面有多個相同的url,後面的並沒有做特殊處理.

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.