5

Is there a way to set subscript and superscript for specific character in the TextView? I want to display a text that looks like this:

enter image description here

So,I tried this code:

TextView tv1 = ... ;
String latex = "\u222E";
tv1.setText(Html.fromHtml(latex + "<sup>200</sup><sub>2</sub> f(x)dx"));

But the result is this:

enter image description here

You can see the superscript appears after the subscript.How I can solve this problem?Can I solve it with SpannableString? Or can I change the position of subscript?

hasanghaforian
  • 13,858
  • 11
  • 76
  • 167
  • create your own Span by extending ReplacementSpan – pskink Feb 21 '14 at 08:48
  • @pskink Can you explain it more or tell me some link to help me to know how to do it,please? Thank you. – hasanghaforian Feb 21 '14 at 09:00
  • I am not sure, but you probably can solve this with SubscriptSpan and SuperscriptSpan.
    Please read this [post](http://flavienlaurent.com/blog/2014/01/31/spans/) and try. It will be useful anyway.
    – x90 Feb 21 '14 at 08:16

1 Answers1

2

this custom span can help you understand the base idea:

class SupSubSpan extends ReplacementSpan {
    private String sup;
    private String sub;

    public SupSubSpan(String sup, String sub) {
        this.sup = sup;
        this.sub = sub;
    }

    @Override
    public int getSize(Paint paint, CharSequence text, int start, int end, FontMetricsInt fm) {
        return (int) Math.max(paint.measureText(sup), paint.measureText(sub));
    }

    @Override
    public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
        canvas.drawText(sup, x, y + paint.ascent() / 2, paint);
        canvas.drawText(sub, x, y - paint.ascent() / 2, paint);
    }
}
pskink
  • 23,874
  • 6
  • 66
  • 77