據我所知,DrawableMarginSpan用於添加一個drawable到段落的主角,同時設置段落的相應的主角magrin,所以這個span不能用來完成你想要的。
你可以嘗試使用ReplacementSpan,它可以繪製你想要的。
/**
* Make drawable as the superscript
*/
public class SuperscriptDrawableSpan extends ReplacementSpan {
private Drawable mDrawable;
private int mWidth;
private int mHeight;
public SuperscriptDrawableSpan(Drawable drawable, int width, int height) {
this.mDrawable = drawable;
this.mWidth = width;
this.mHeight = height;
}
@Override
public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
return mWidth;
}
@Override
public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
mDrawable.setBounds((int) x, top, ((int) x) + mWidth, top + mHeight);
mDrawable.draw(canvas);
}
}
然後,你可以使用它作爲其他xxxSpan:
mSpannableBuilder = new SpannableStringBuilder();
mSpannableBuilder.append("SuperScriptDrawable^");
SuperscriptDrawableSpan spanSuperscriptDeawable = new SuperscriptDrawableSpan(getActivity().getResources().getDrawable(R.mipmap.ic_launcher), 24, 24);
mSpannableBuilder.setSpan(span, mSpannableBuilder.length() - 1,
mSpannableBuilder.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
只是爲了演示,使用時需要優化。