Android将文本中的URL转换为超链接工具类(原文本有超链接标签也适用)

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 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 += "" + url + ""; 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 += "" + urlSpan.getText() + ""; }} 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; } } }

    推荐阅读