package com.kuaibao.skuaidi.texthelp;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TextToLink {
/**
* URL转换为链接
* @author 顾冬冬
* @param urlText
* @return String
*/
public static String urlToLink(String urlText){
// url的正则表达式
String regexp = "((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)"; // 结束条件
Pattern pattern = Pattern.compile(regexp, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(urlText);
String resultText = "";// (临时变量,保存转换后的文本)
int lastEnd = 0;// 保存每个链接最后一会的下标
while(matcher.find()){
resultText += urlText.substring(lastEnd, matcher.start()-1);
resultText += "<a href=\"" + matcher.group() + "\">" + matcher.group() + "</a>";
lastEnd = matcher.end();
}
resultText += urlText.substring(lastEnd);
return resultText;
}
}
在这里需要说明的方法:
matcher.find()
最后,将上面返回的结果设置到文本框中,不过要注意的是下面两行代码(必须设置了才可以点击和转换哦):
tv_notice_content.setText(Html.fromHtml(TextToLink.urlToLink(带链接的文本)));//
tv_notice_content.setMovementMethod(LinkMovementMethod.getInstance());// 对这个控件设置了以后就可以点击 了
tv_notice_content.setText(Html.fromHtml("<a href=\"" + <a target=_blank href="http://www.baidu.com">http://www.baidu.com</a> + "\">" + "《点击查看》" + "</a"));
上面这行代码呢就是将“《点击查看》”用来代替前面那段链接了。
如果有什么疑问一定要给我留言哦~我不怕批评,哈哈~望不吝赐教