Search code examples
androidtextviewsubscriptsuperscript

Setting subscript and superscript for specific character in the TextView?


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?


Solution

  • 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);
        }
    }