/**
* 文本中Url检测处理
*
* @author: NPF
* @date: 2018/1/15.
*/
public class UrlFilter {
/**
* URL匹配正则
*/
private static final String REGEX_URL = "((http(s)?|(ftp))://)?([a-z]+\\.)?[a-z\\d]+\\.[a-z\\d]+([/^a-z\\d\\.\\?]+)?([a-z\\d=&]+)?";
private static UrlFilter mInstance = null;
private UrlFilter() {
}
public UrlFilter getInstance() {
if (null == mInstance) {
synchronized (UrlFilter.class) {
if (null == mInstance) {
mInstance = new UrlFilter();
}
}
}
return mInstance;
}
/**
* URL过滤
*
* @param str 需要处理的字符串
* @param inter 匹配到的url点击事件回调
* @return
*/
public SpannableString urlFilter(String str, UrlClickInter inter) {
SpannableString spannableString = new SpannableString(str);
Pattern sinaPattenUrl = Pattern.compile(REGEX_URL, Pattern.CASE_INSENSITIVE);
try {
urlFilter(spannableString, sinaPattenUrl, 0, inter);
} catch (Exception e) {
e.printStackTrace();
return new SpannableString("");
}
return spannableString;
}
/**
* URL过滤
*
* @param spannableString
* @param patten
* @param start
* @param inter
*/
private void urlFilter(final SpannableString spannableString, Pattern patten, int start, final UrlClickInter inter) {
try {
final Matcher matcher = patten.matcher(spannableString);
int end = -1;
while (matcher.find()) {
String key = matcher.group();
if (matcher.start() < start) {
continue;
}
end = matcher.start() + key.length();
initUrlClick(spannableString, matcher.start(), end, inter);
break;
}
if (end != -1 && end < spannableString.length()) {
urlFilter(spannableString, patten, end, inter);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 处理Url点击事件
*
* @param spannableString
* @param start
* @param end
* @param inter
*/
private void initUrlClick(final SpannableString spannableString, final int start, final int end, final UrlClickInter inter) {
spannableString.setSpan(new ClickableSpan() {
@Override
public void onClick(View widget) {
inter.onClick(spannableString.subSequence(start, end).toString());
}
@Override
public void updateDrawState(TextPaint ds) {
ds.setColor(ds.linkColor);
ds.setUnderlineText(false);
}
}, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
/**
* 事件回调
*/
public interface UrlClickInter {
void onClick(String url);
}
}