我想在多行字符串中的每行末尾添加一个span。我试图画一个字符,但没有出现在行尾。但是当设置ImageSpan
时,它可以增加行高,但行中仍然没有图像。
private void addSpansAtEnd() {
String s = "First line\nSecond line\Third line\n";
SpannableStringBuilder e = new SpannableStringBuilder(s);
int stop = start + count;
for (int start = -1;
(start = s.indexOf("\n", start)) > -1 && start < stop;
++start) {
e.setSpan(
/*new ImageSpan(getContext(), R.drawable.ic_line),*/
new NewLineSpan(),
start,
start + 1,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
/* Trying to replace \\n with other character. */
private class NewLineSpan extends ReplacementSpan {
@Override
public int getSize(
Paint paint,
CharSequence text,
int start,
int end,
Paint.FontMetricsInt fm) {
return 0;
}
@Override
public void draw(
Canvas canvas,
CharSequence text,
int start,
int end,
float x,
int top,
int y,
int bottom,
Paint paint) {
paint.setColor(0xFF666666);
canvas.drawText("o", x, y, paint);
}
}
如何在行尾绘制?
答案 0 :(得分:1)
在换行符上放一个跨度似乎有点奇怪。换行符有两行,但没有任何宽度。如果你在换行符之前添加一个空格然后将空间放在空间周围,我想你可能会有更多的运气:
for (int start = -1;
(start = s.indexOf("\n", start)) > -1 && start < stop;
start += 2) { // increment by 2 to skip the displaced newline
e.insert(start, " "); // insert a space for the span
e.setSpan(new ImageSpan(getContext(), R.drawable.ic_line),
start,
start + 1,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
stop++; // because a space was added
}