I set background in string like that:
spanString.setSpan(new BackgroundColorSpan(color), 0, 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
But I would l
Looks like I found a working (but hacky) solution to this problem. Try to add another symbol to the end of the string so that it isn't included in the span - and then draw()
gets called!
char EXTRA_SPACE = ' ';
String text = originalString + EXTRA_SPACE;
Spannable spannable = new SpannableString(text);
spannable.setSpan(new MyReplacementSpan(), 0, text.length()-1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
textView.setText(spannable);
Looks like it ignores the spans which are whole string wide.
In case anyone has this problem, I encountered it. What I had to do is to pass a second parameter into the setText() method. My call looked like
textView.setText(spanned, TextView.BufferType.SPANNABLE);
Hope this helps!
Even if you return the width of the span, the height of the span is 0 when the span covers the whole string. Therefore your span is actually there, with the specified width but the height is 0, therefore not drawn.
You have to set the height of the span updating the values of the parameter Paint.FontMetricsInt fm for function getSize. Check the DynamicDrawable.getSize function as a reference to set the height by updating the FontMetrics values.
In method getSize()
the Paint.FontMetricsInt fm
must be recalculated based on paint
FontMetricsInt:
@Override
public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
width = Math.round(paint.measureText(text, start, end));
Paint.FontMetricsInt metrics = paint.getFontMetricsInt();
if (fm != null) {
fm.top = metrics.top;
fm.ascent = metrics.ascent;
fm.descent = metrics.descent;
fm.bottom = metrics.bottom;
}
return width;
}
The documentation for ReplacementSpan.getSize() provides the answer:
Returns the width of the span. Extending classes can set the height of the span by updating attributes of Paint.FontMetricsInt. If the span covers the whole text, and the height is not set, draw() will not be called for the span.
Make sure to update Paint.FontMetricsInt
with proper values to fix the problem.
In my case, I just took the metrics from the TextView
's Paint
:
@Override
public int getSize(
Paint paint,
CharSequence text,
int start,
int end,
Paint.FontMetricsInt fm) {
final Paint.FontMetrics paintFontMetrics = paint.getFontMetrics();
if (fm != null) {
fm.ascent = (int) paintFontMetrics.ascent;
fm.bottom = (int) paintFontMetrics.bottom;
fm.descent = (int) paintFontMetrics.descent;
fm.leading = (int) paintFontMetrics.leading;
fm.top = (int) paintFontMetrics.top;
}
//...
}
I think it helps to you. Set textView width match parent. main_activity.xml
<TextView
android:width="match_parent"