android字符串加空格,如何在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);

}

}

我从上面得到的结果是:

zM8RB.png

上面代码的问题是:

>如何在两个spannable字符串之间添加空格?

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

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

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

1iAay.png

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

我怎样才能使它正确?

编辑-1

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

1WbGB.png

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值