如何在Android中的spannable字符串之间腾出空间?

码:

private void setSpans(Editable s, @ColorInt int backgroundColor) { BackgroundColorSpan[] spans = s.getSpans(0, s.length(), BackgroundColorSpan.class); String[] words; if (s.toString().endsWith(" ")) { words = (s.toString() + "X").split("\\s"); } else { words = s.toString().split("\\s"); } int completedWordsCount = words.length - 1; if (spans.length != completedWordsCount) { for (BackgroundColorSpan span : spans) { s.removeSpan(span); } int currentIndex = 0; for (int i = 0; i < words.length-1; i++) { s.setSpan(new CustomDrawble(Color.GRAY, Color.WHITE), currentIndex, currentIndex + words[i].length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); currentIndex += words[i].length() + 1; } } 

上面的函数对于创建spannable String并向其添加Border非常有用。 我打电话给下课:

 public class CustomDrawble extends ReplacementSpan { private int mBackgroundColor; private int mForegroundColor; public CustomDrawble(int backgroundColor, int foregroundColor) { this.mBackgroundColor = backgroundColor; this.mForegroundColor = foregroundColor; } @Override public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) { return Math.round(measureText(paint, 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) { float padding = 4f; RectF rect = new RectF(x, top + 3, x + measureText(paint, text, start, end) + 10, bottom + 10); paint.setColor(mBackgroundColor); canvas.drawRoundRect(rect, 10,10,paint); paint.setColor(mForegroundColor); canvas.drawText(text, start, end, x, y, paint); } private float measureText(Paint paint, CharSequence text, int start, int end) { return paint.measureText(text, start, end); } } 

我从上面得到的结果是:

在此处输入图像描述

上面代码的问题是:

  • 如何在两个spannable字符串之间添加空格?
  • 如何在矩形的起点和类似于矩形结尾的字符串的第一个字符处添加空格。 我尝试通过以下代码添加空间:

     RectF rect = new RectF(x+10, top + 3, x + measureText(paint, text, start, end) + 10, bottom + 10); 

但它给了我这个扭曲的结果:

在此处输入图像描述

如果我没有错,那么上面代码的问题是两个spannable字符串之间没有足够的空格。

我怎样才能使它正确?

编辑-1

使用此RectF rect = new RectF(x - 5, top + 3, x + measureText(paint, text, start, end)+5, bottom + 10);

在此处输入图像描述

看看第一个从起点略微切割的。 但如果我使用上面的配置,我在两个字符串中没有足够的空间。 这是主要问题。

rect末端删除多余的像素将解决跨距之间没有空间的问题

所以从param中删除+ 10为正确

像这样:

 RectF rect = new RectF(x, top + 3, x + measureText(paint, text, start, end), bottom + 10); 

也是为了在开始时添加空间,在这样开始时加上一些负余量:

  RectF rect = new RectF(x - 5, top + 3, x + measureText(paint, text, start, end), bottom + 10); 

下面的图片将直观地解释:

挖