Android Linkify - Clickable telephone numbers

混江龙づ霸主 提交于 2019-12-07 07:41:36

问题


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


回答1:


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())



回答2:


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());



回答3:


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



来源:https://stackoverflow.com/questions/27927930/android-linkify-clickable-telephone-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!