【发布时间】:2018-06-13 03:57:08
【问题描述】:
我有一条包含我们电话号码的短信。无论电话语言是什么,我都想让它们可点击。我调查了自动链接的工作原理,发现了我尝试在自定义 TextView 上使用的 Linkify.addLinks 方法。
public class PhoneNumberLinkTextView extends android.support.v7.widget.AppCompatTextView {
public PhoneNumberLinkTextView(Context context) {
super(context);
}
public PhoneNumberLinkTextView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public PhoneNumberLinkTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void setUSNumberText(CharSequence text) {
SpannableStringBuilder spanText = new SpannableStringBuilder(text);
if (addLinks(spanText)) {
setText(spanText);
} else {
setText(text);
}
}
public boolean addLinks(@NonNull SpannableStringBuilder text) {
ArrayList<LinkSpec> links = new ArrayList<>();
gatherTelLinks(links, text);
if (links.isEmpty()) {
return false;
}
Object[] spans = text.getSpans(0, text.length(), Object.class);
final int count = spans.length;
for (int i = 0; i < count; i++) {
text.removeSpan(spans[i]);
}
for (LinkSpec link: links) {
applyLink(link.url, link.start, link.end, text);
}
return true;
}
private void gatherTelLinks(ArrayList<LinkSpec> links, Spannable s) {
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
Iterable<PhoneNumberMatch> matches = phoneUtil.findNumbers(s.toString(),
Locale.US.getCountry(), PhoneNumberUtil.Leniency.POSSIBLE, Long.MAX_VALUE);
for (PhoneNumberMatch match : matches) {
LinkSpec spec = new LinkSpec();
spec.url = "tel:" + normalizeNumber(match.rawString());
spec.start = match.start();
spec.end = match.end();
links.add(spec);
}
}
private void applyLink(String url, int start, int end, Spannable text) {
URLSpan span = new URLSpan (url);
text.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
/**
* Normalize a phone number by removing the characters other than digits. If
* the given number has keypad letters, the letters will be converted to
* digits first.
*
* @param phoneNumber the number to be normalized.
* @return the normalized number.
*/
public String normalizeNumber(String phoneNumber) {
if (TextUtils.isEmpty(phoneNumber)) {
return "";
}
StringBuilder sb = new StringBuilder();
int len = phoneNumber.length();
for (int i = 0; i < len; i++) {
char c = phoneNumber.charAt(i);
// Character.digit() supports ASCII and Unicode digits (fullwidth, Arabic-Indic, etc.)
int digit = Character.digit(c, 10);
if (digit != -1) {
sb.append(digit);
} else if (sb.length() == 0 && c == '+') {
sb.append(c);
} else if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
return normalizeNumber(PhoneNumberUtils.convertKeypadLettersToDigits(phoneNumber));
}
}
return sb.toString();
}
class LinkSpec {
String url;
int start;
int end;
}
}
此代码目前在视觉上工作。我的美国号码的格式符合我的预期,但我的电话号码不可点击。
然后我尝试在我的 setText() 之后添加一个 setMovementMethod(LinkMovementMethod.getInstance()),但这次我丢失了格式化为电话号码的美国号码。
有谁知道我怎样才能实现我想要做的事情?
【问题讨论】: