Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 801
James King Avatar asked Jan 13 '15 17:01

James King


2 Answers

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())
like image 157
John Cummings Avatar answered Nov 20 '22 07:11

John Cummings


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());
like image 32
Nick Pontiff Avatar answered Nov 20 '22 08:11

Nick Pontiff