Is there a standard way to have hrefs and phone numbers that can be clicked in a TextView?

I already know how to use TextView to automatically create interactive links for web addresses, phone numbers, etc. My question is when you have hrefs HTML code as well as phone numbers and you want both to be clickable, is there a better or more standard way to do this? Here is what I have:

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:"); 

This code works, but does not seem ideal. I DO NOT call setAutoLinkMask (Linkify.PHONE_NUMBERS) because it will ignore href in the HTML and it will destroy the Spannables, which Html.fromHtml will add even when creating Linkify.WEB_URLS.

At least I would like to use a more reliable or standard REGEX for phone numbers. I think something like Patterns.PHONE will at least be the best regex. However, I hope there is a more elegant solution that I had above.

0
source share
1 answer

You can use the cutom implementation LinkMovementMethod . Like this:

 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; } } 
0
source

Source: https://habr.com/ru/post/886457/


All Articles