DrawableMarginSpan usage example?
I'm working with spannable text, basically replacing tokens like this^ with drawables. This seems to work fine except that i'm having a tough time with the placement. I actually want the drawable to have the appearance of Super Script text but I can't get it to work. I was thinking that maybe i could use the DrawableMarginSp开发者_如何学Pythonan class to set the bottom margin of my drawable, but this doesn't seem to work.
The documentation gives me nothing and I already ran many google searches to no avail. http://developer.android.com/reference/android/text/style/DrawableMarginSpan.html
Any info or suggestions on how I can accomplish this will me much appreciated. :)
As far as I know, DrawableMarginSpan is used to add a drawable to the leading of paragraph, while set the corresponding leading magrin of the paragraph, so this Span can't be used to accomplish what you want.
You can have a try to use ReplacementSpan, which can draw what you want.
/**
* 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);
}
}
Then, you can use it as other 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);
Just for demo, need optimization when used.
精彩评论