if (mAutoLinkMask != 0) {
Spannable s2;
if (type == BufferType.EDITABLE || text instanceof Spannable) {
s2 = (Spannable) text;
} else {
s2 = mSpannableFactory.newSpannable(text);
}
if (Linkify.addLinks(s2, mAutoLinkMask)) {
text = s2;
type = (type == BufferType.EDITABLE) ? BufferType.EDITABLE : BufferType.SPANNABLE;
/*
-
We must go ahead and set the text before changing the
-
movement method, because setMovementMethod() may call
-
setText() again to try to upgrade the buffer type.
*/
setTextInternal(text);
// Do not change the movement method for text that support text selection as it
// would prevent an arbitrary cursor displacement.
if (mLinksClickable && !textCanBeSelected()) {
setMovementMethod(LinkMovementMethod.getInstance());
}
}
}
-
首先调用 Linkify.addLinks 方法解析 autolink 的相关属性
-
判断是否 mLinksClickable mLinksClickable && !textCanBeSelected() ,若返回 true, 设置 setMovementMethod
我们先来看一下 Linkify 类, 里面定义了几个常量, 分别对应 web , email ,phone ,map,他们的值是位上错开的,这样定义的好处是
-
方便组合多种值
-
组合值之后不会丢失状态,即可以获取是否含有某种状态, web, email, phone , map
public class Linkify {
public static final int WEB_URLS = 0x01;
public static final int EMAIL_ADDRESSES = 0x02;
public static final int PHONE_NUMBERS = 0x04;
public static final int MAP_ADDRESSES = 0x08;
}
看一下 linkify 的 addLinks 方法
-
根据 mask 的标志位,进行相应的正则表达式进行匹配,找到 text 里面的相应的 WEB_URLS, EMAIL_ADDRESSES, PHONE_NUMBERS, MAP_ADDRESSES. 并将相应的文本从 text 里面移除,封装成 LinkSpec,并添加到 links 里面
-
遍历 links,设置相应的 URLSpan
private static boolean addLinks(@NonNull Spannable text, @LinkifyMask int mask,
@Nullable Context context) {
if (mask == 0) {