这个答案扩展了Jonathan S的出色解决方案:
您可以使用以下方法从文本中提取链接:
private static ArrayList<String> getLinksFromText(String text) {
ArrayList links = new ArrayList();
String regex = "\(?\b((http|https)://www[.])[-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_()|]";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(text);
while (m.find()) {
String urlStr = m.group();
if (urlStr.startsWith("(") && urlStr.endsWith(")")) {
urlStr = urlStr.substring(1, urlStr.length() - 1);
}
links.add(urlStr);
}
return links;
}
这可用于删除clickify()
方法中的参数之一:
public static void clickify(TextView view,
final ClickSpan.OnClickListener listener) {
CharSequence text = view.getText();
String string = text.toString();
ArrayList<String> linksInText = getLinksFromText(string);
if (linksInText.isEmpty()){
return;
}
String clickableText = linksInText.get(0);
ClickSpan span = new ClickSpan(listener,clickableText);
int start = string.indexOf(clickableText);
int end = start + clickableText.length();
if (start == -1) return;
if (text instanceof Spannable) {
((Spannable) text).setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
} else {
SpannableString s = SpannableString.valueOf(text);
s.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
view.setText(s);
}
MovementMethod m = view.getMovementMethod();
if ((m == null) || !(m instanceof LinkMovementMethod)) {
view.setMovementMethod(LinkMovementMethod.getInstance());
}
}
对ClickSpan的一些更改:
public static class ClickSpan extends ClickableSpan {
private String mClickableText;
private OnClickListener mListener;
public ClickSpan(OnClickListener listener, String clickableText) {
mListener = listener;
mClickableText = clickableText;
}
@Override
public void onClick(View widget) {
if (mListener != null) mListener.onClick(mClickableText);
}
public interface OnClickListener {
void onClick(String clickableText);
}
}
现在,您只需在TextView上设置文本,然后向其添加侦听器:
TextViewUtils.clickify(textWithLink,new TextUtils.ClickSpan.OnClickListener(){
@Override
public void onClick(String clickableText){
//action...
}
});