我已经知道如何使用TextView自动为网址,电话号码等创建可点击链接。我的问题是当你的HTML中包含hrefs以及电话号码时你想要两个都可点击,是否有更好或更标准的做法?这就是我所拥有的:
String text = "Click <a href=\"http://stackoverflow.com\">Stackoverflow</a> or call 1-234-567-8901.";
TextView textView = getTextView();
textView.setLinksClickable(true);
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setText(Html.fromHtml(text));
// This is a pretty primitive US-centric phone number REGEX but it works
Linkify.addLinks(textView, Pattern.compile("(1?[-. ])?\\d\\d\\d([-. ])\\d\\d\\d\\2\\d\\d\\d\\d"), "tel:");
此代码有效,但似乎并不理想。我不调用setAutoLinkMask(Linkify.PHONE_NUMBERS),因为它会忽略HTML中的href,它会消除Html.fromHtml添加的Spannables,即使创建了Linkify.WEB_URLS。
至少我想为电话号码使用更强大或标准的REGEX。我认为像Patterns.PHONE这样的东西至少会是一个更好的正则表达式。但是,我希望有一个更优雅的解决方案,就像我上面所做的那样。
答案 0 :(得分:0)
您可以使用自定义LinkMovementMethod
实施。像这样:
public class CustomLinkMovementMethod extends LinkMovementMethod {
private static CustomLinkMovementMethod linkMovementMethod = new BayerLinkMovementMethod();
public boolean onTouchEvent(TextView widget, Spannable buffer,
MotionEvent event) {
int action = event.getAction();
if (action == MotionEvent.ACTION_UP) {
int x = (int) event.getX();
int y = (int) event.getY();
x -= widget.getTotalPaddingLeft();
y -= widget.getTotalPaddingTop();
x += widget.getScrollX();
y += widget.getScrollY();
Layout layout = widget.getLayout();
int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x);
URLSpan[] link = buffer.getSpans(off, off, URLSpan.class);
if (link.length != 0) {
String url = link[0].getURL();
if (url.startsWith("http://") || url.startsWith("https://")) {
//do anything you want
} else if (url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_DIAL,
Uri.parse(url));
widget.getContext().startActivity(intent);
return true;
} else if (url.startsWith("mailto:")) {
Intent intent = new Intent(Intent.ACTION_SENDTO,
Uri.parse(url));
widget.getContext().startActivity(intent);
return true;
}
return true;
}
}
return super.onTouchEvent(widget, buffer, event);
}
public static MovementMethod getInstance() {
return linkMovementMethod;
}
}