sb.setSpan(new ReplacementSpan() { @Override public int getSize(Paint paint, CharSequence text, int start, int end, FontMetricsInt fm) { //最后一个参数为end-1,防止这个span最后与下一个字符之间有空格 if (fm != null) { paint.getFontMetricsInt(fm); } return (int) paint.measureText(text, start, end); } @Override public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) { // String newText = "****" + text.toString().substring(start + 4, end); paint.setUnderlineText(true); paint.setColor(linkColor); canvas.drawText("****", 0, end - start, x, y, paint); } }, start, start + 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);在画这个span之前要先设置覆盖的那几个字符typeface是monospace(等宽字符)的,不然就会出现空格、重叠等现象
代码如下:
sb.setSpan(new TypefaceSpan("monospace"), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);