public class TextToLinkUtil {
public static String textContainUrlToLink(String urlText) {
// 先拆分原字符串的超链接和文本
Spanned spanned = Html.fromHtml(urlText);
SpannableStringBuilder builder = new SpannableStringBuilder(spanned);
URLSpan[] spans = builder.getSpans(0, builder.length(), URLSpan.class);
String newUrlText = builder.toString();
ArrayList<Object> list = new ArrayList<>();
if (spans != null) {
int index = 0;
for (URLSpan urlSpan : spans) {
int start = builder.getSpanStart(urlSpan);
int end = builder.getSpanEnd(urlSpan);
if (start >= 0 && end >= 0) {
if(start <= newUrlText.length()) {
list.add(newUrlText.substring(index, start));
}
if(end <= newUrlText.length()) {
list.add(new TextUrlSpan(newUrlText.substring(start, end), urlSpan.getURL()));
}
index = end;
}
}
if(index >= 0) {
list.add(newUrlText.substring(index, newUrlText.length()));
}
} else {
list.add(newUrlText);
}
//再用正则表达式匹配文本中的链接,最后把超链接和匹配到的链接文本合并
// url的正则表达式
String regexp = "((http[s]{0,1})://[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);
String newStr = "";
for (int i = 0; i < list.size(); i++) {
if (list.get(i) instanceof String) {
String str = (String) list.get(i);
Matcher matcher = pattern.matcher(str);
String resultText = "";// (临时变量,保存转换后的文本)
int lastEnd = 0;// 保存每个链接最后一会的下标
while (matcher.find()) {
if (lastEnd >=0 && matcher.start() >=0 && matcher.start() <= str.length()) {
resultText += str.substring(lastEnd, matcher.start());
}
String url = matcher.group();
//匹配到没有协议的链接,默认使用http
if(!url.startsWith("http") && !url.startsWith("https")) {
url = "http://" + url;
}
resultText += "<a href=\"" + url+ "\">" + url + "</a>";
lastEnd = matcher.end();
}
if(lastEnd >= 0) {
resultText += str.substring(lastEnd);
}
newStr += resultText;
} else if (list.get(i) instanceof TextUrlSpan) {
TextUrlSpan urlSpan = (TextUrlSpan) list.get(i);
String url = urlSpan.getURL();
//匹配到没有协议的链接,默认使用http
if(!url.startsWith("http") && !url.startsWith("https")) {
url = "http://" + url;
}
newStr += "<a href=\"" + url + "\">" + urlSpan.getText() + "</a>";
}
}
return newStr;
}
private static class TextUrlSpan extends URLSpan {
private String text;
public String getText() {
return text;
}
public TextUrlSpan(String text, String url) {
super(url);
this.text = text;
}
}
}
Android将文本中的URL转换为超链接工具类(原文本有超链接标签也适用)
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 今天是旅行的最后一天了,我们要去泡温泉。早上起床后,女儿自己洗刷完毕,我们去餐厅吃早饭。女儿照顾着朋友的女儿...