Android 字符串中选出手机号变色加点击事件去除下划线

Android 字符串中选出手机号变色加点击事件去除下划线_第1张图片

1.字符串截取手机号方法

   public String getPhone(String sParam) {
        if (sParam.length() <= 0)
            return "";
        Pattern pattern = Pattern.compile("(1|861)(3|5|8)\\d{9}$*");
        Matcher matcher = pattern.matcher(sParam);
        StringBuffer bf = new StringBuffer();
        while (matcher.find()) {
            bf.append(matcher.group()).append(",");
        }
        int len = bf.length();
        if (len > 0) {
            bf.deleteCharAt(len - 1);
        }
        return bf.toString();
    }

2.改变手机号颜色并添加点击事件

private TextView mContactNone;  
public void showRequestFailInviteRecord(String desc, String str) {
        mContactNone = findViewById(R.id.mContactNone);
        //创建 SpannableString 对象
        SpannableString mStyledText = new SpannableString(desc);
        //   mStyledText.setSpan(new ForegroundColorSpan(Color.BLUE), 7, 18, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        Pattern mPattern = Pattern.compile(str);
        Matcher mMatcher = mPattern.matcher(desc);
        while (mMatcher.find()) {
            ClickableSpan what = new ClickableSpan() {
                @Override
                public void onClick(View view) {
                    //这里的代码是对按钮点击事件的处理。。。。。。
                    Toast.makeText(MainActivity.this, "点击了", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void updateDrawState(TextPaint ds) {
                    super.updateDrawState(ds);
                    ds.setUnderlineText(false);//去掉下划线
                    ds.setColor(getResources().getColor(R.color.colorPrimary));//设置字体颜色

                }
            };
            mStyledText.setSpan(what, mMatcher.start(), mMatcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            mContactNone.setText(mStyledText);
            mContactNone.setMovementMethod(LinkMovementMethod.getInstance());
            mContactNone.setHighlightColor(getResources().getColor(android.R.color.transparent));
        }
    }

3.调用方法


String string = "截取手机号13691032316变色加点击事件";

showRequestFailInviteRecord(string, getPhone(string));

 

你可能感兴趣的:(Android 字符串中选出手机号变色加点击事件去除下划线)