我正在尝试在文本错误下面添加红色波浪线,例如:
不幸的是,我找不到合适的*SPAN类来包装错误文本。
我应该如何在android中实现这样的功能?
最佳答案
我通过实现自定义范围解决了这个问题:
将error_underline.png
添加到您的资源中:然后使用此类创建跨距:
static class ErrorSpan extends DynamicDrawableSpan {
private BitmapDrawable mRedWavy;
private int mWidth;
private int mBmpHeight;
ErrorSpan(Resources resources) {
super(DynamicDrawableSpan.ALIGN_BASELINE);
mRedWavy = new BitmapDrawable(resources, BitmapFactory.decodeResource(resources, R.drawable.error_underline));
mBmpHeight = mRedWavy.getIntrinsicHeight();
mRedWavy.setTileModeX(TileMode.REPEAT);
}
@Override
public Drawable getDrawable() {
return mRedWavy;
}
@Override
public int getSize(Paint paint, CharSequence text,
int start, int end,
Paint.FontMetricsInt fm) {
mWidth = (int) paint.measureText(text, start, end);
return mWidth;
}
@Override
public void draw(Canvas canvas, CharSequence text,
int start, int end, float x,
int top, int y, int bottom, Paint paint) {
mRedWavy.setBounds(0, 0, mWidth, mBmpHeight);
canvas.save();
canvas.translate(x, bottom-mBmpHeight);
mRedWavy.draw(canvas);
canvas.restore();
canvas.drawText(text.subSequence(start, end).toString(), x, y, paint);
}
}