James King
James King

Reputation: 2445

Android Linkify - Clickable telephone numbers

So I am trying to add the functionality that when you click on a phone number it would take you to the Dialer app with the pre-populated number. I have the code below:

mContactDetailsText.setText(phonetextBuilder.toString());
            Pattern pattern = Pattern.compile("[0-9]+\\s+[0-9]+");
            Linkify.addLinks(mContactDetailsText, pattern, "tel:");

and the Text is currently "T. 0123 4567890"

The current outcome is just having the above string without it being clickable. I have even tried added the following line, but to no luck:

mContactDetailsText.setAutoLinkMask(0);

Anyone got any ideas or can see what I am doing wrong?

Thanks

Upvotes: 5

Views: 6983

Answers (3)

John Cummings
John Cummings

Reputation: 2184

The autolink mask needs to include a search for phone numbers:

mContactDetailsText.setAutoLinkMask(Linkify.PHONE_NUMBERS);

Then you'll need to set the links to be clickable:

mContactDetailsText.setLinksClickable(true);

You might also need movement method set like so:

mContactDetailsText.setMovementMethod(LinkMovementMethod.getInstance())

Upvotes: 10

Nick Pontiff
Nick Pontiff

Reputation: 144

You should be able to accomplish what you want with the other answers, but this will definitely work and will give you more control over the display of the text and what will happen when you click the number.

 String text = "T. ";
 StringBuilder stringBuilder = new StringBuilder(text);
 int phoneSpanStart = stringBuilder.length();
 String phoneNumber = "0123 4567890"
 stringBuilder.append(phoneNumber);
 int phoneSpanEnd = stringBuilder.length();

 ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void onClick(View textView) {
                Intent intent = new Intent(Intent.ACTION_DIAL);
                intent.setData(Uri.parse("tel:" + phoneNumber.replace(" ", "")));
                startActivity(intent); 
            }

            public void updateDrawState(TextPaint ds) {// override updateDrawState
                ds.setUnderlineText(false); // set to false to remove underline
                ds.setColor(Color.BLUE);
            }
        };
   SpannableString spannableString = new SpannableString(stringBuilder);
   spannableString.setSpan(clickableSpan, phoneSpanStart, phoneSpanEnd,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

 myTextView.setText(spannableString);
 myTextView.setMovementMethod(LinkMovementMethod.getInstance());

Upvotes: 4

IgorGanapolsky
IgorGanapolsky

Reputation: 26831

You need to set an onClickListener() on your TextViews. Then they will respond to clicks.

Upvotes: 0

Related Questions