这是我的调查。
我创建了一个新项目,并将android:autoLink="all" 添加到activity_main.xml 的文本视图中。感谢 Android Studio 的开发者,我看到了预览,发现了一些有趣的东西:
-
12345 未链接
-
123456 未链接
-
1234567 已链接
-
12345678 已链接
-
123456789 未链接
-
1234567890 不喜欢
-
12345678901 已链接
-
123456789012 未链接
结果在我的手机上是一样的。于是我查看了源代码,搜索了关键字autolink,然后我发现了这个:
private void setText(CharSequence text, BufferType type,
boolean notifyBefore, int oldlen) {
...
// unconcerned code above
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.
*/
mText = 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());
}
}
}
...
// unconcerned code above
}
所以现在关键字是Linkify。对于addLinks:
public static final boolean addLinks(@NonNull Spannable text, @LinkifyMask int mask) {
...
if ((mask & PHONE_NUMBERS) != 0) {
gatherTelLinks(links, text);
}
...
}
private static final void gatherTelLinks(ArrayList<LinkSpec> links, Spannable s) {
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
Iterable<PhoneNumberMatch> matches = phoneUtil.findNumbers(s.toString(),
Locale.getDefault().getCountry(), Leniency.POSSIBLE, Long.MAX_VALUE);
for (PhoneNumberMatch match : matches) {
LinkSpec spec = new LinkSpec();
spec.url = "tel:" + PhoneNumberUtils.normalizeNumber(match.rawString());
spec.start = match.start();
spec.end = match.end();
links.add(spec);
}
}
然后,不好的事情发生了,SDK没有PhoneNumberUtil,特别是下面这3个类:
import com.android.i18n.phonenumbers.PhoneNumberMatch;
import com.android.i18n.phonenumbers.PhoneNumberUtil;
import com.android.i18n.phonenumbers.PhoneNumberUtil.Leniency;
目前,第一个原因浮出水面:Locale.getDefault().getCountry()。
所以我去设置,找到语言,选择中文。结果如下:
-
12345 已链接
-
123456 已链接
-
1234567 已链接
-
12345678 已链接
-
123456789 已链接
-
1234567890 已链接
-
12345678901 已链接
-
123456789012 已链接
其次,对于com.android.i18n.phonenumbers的包,我发现了这个:
https://android.googlesource.com/platform/external/libphonenumber/+/ics-factoryrom-2-release/java/src/com/android/i18n/phonenumbers
如果您有兴趣,请查看上面的链接。请注意 URL:ics-factoryrom-2-release。所以我非常怀疑这是平台相关。
对于解决方案,CleverAndroid 是对的,完全控制LinkMovementMethod 是一个不错的选择。