步骤1:创建自己的ClickableSpan
子类,使其在onClick()
方法中实现所需功能(例如,命名为YourCustomClickableSpan
)
步骤2:运行批量转换所有URLSpan
对象为YourCustomClickableSpan
对象。我有一个实用类可供使用:
public class RichTextUtils {
public static <A extends CharacterStyle, B extends CharacterStyle> Spannable replaceAll(Spanned original,
Class<A> sourceType,
SpanConverter<A, B> converter) {
SpannableString result=new SpannableString(original);
A[] spans=result.getSpans(0, result.length(), sourceType);
for (A span : spans) {
int start=result.getSpanStart(span);
int end=result.getSpanEnd(span);
int flags=result.getSpanFlags(span);
result.removeSpan(span);
result.setSpan(converter.convert(span), start, end, flags);
}
return(result);
}
public interface SpanConverter<A extends CharacterStyle, B extends CharacterStyle> {
B convert(A span);
}
}
你可以像这样使用它:
yourTextView.setText(RichTextUtils.replaceAll((Spanned)yourTextView.getText(),
URLSpan.class,
new URLSpanConverter()));
使用自定义的URLSpanConverter
,像这样:
class URLSpanConverter
implements
RichTextUtils.SpanConverter<URLSpan, YourCustomClickableSpan> {
@Override
public URLSpan convert(URLSpan span) {
return(new YourCustomClickableSpan(span.getURL()));
}
}
将所有URLSpan
对象转换为YourCustomClickableSpan
对象。
ClickableSpan
替换Linkify
生成的URLSpan
对象,以实现你所需的功能。 - CommonsWareonClick
事件。不过我喜欢的是它也可以链接化标签!请把您的评论改写成答案,谢谢您。 - A-Live