Skip to content

How to quickly add Superscript / Subscript

December 28, 2009

Hey everyone,

Quick post today. Here’s how you would add superscript/subscript to your text in a TextView.

TextView text = (TextView) findViewById(R.id.text); // retrieve your text view
text.setText(Html.fromHtml("5x<sup>2</sup>"));

And so your text view should now have 5x2 show up.

It’s as simple as that! And if you want subscripts just replace “< sup >” with “< sub >” and you’re good to go.

Finally, depending on what you’re doing, sometimes it appears that the super/sub scripts are “cutoff” by the text view, and so I’ve found that adding a “< small >” clause to the HTML does the trick:

text.setText(Html.fromHtml("5x<sup><small>2</small></sup>"));

Hope this helped some people!

– jwei

PS: I know there is a TextAttribute class in Android/JAVA that you can use, but I just found this way much simpler.

5 Comments leave one →
  1. Rok permalink
    July 15, 2010 1:20 am

    Great solution! I’ve been looking for this. My superscript text was cutoff in a Spinner element.

  2. Ryan permalink
    October 19, 2010 1:47 pm

    for some reason this solution doesn’t appear to work for strings that are used as listview titles (textviews).. At least in my case

  3. Yogesh permalink
    June 22, 2011 12:17 am

    It creates the superscript but doesn’t make it small… even after adding tag đŸ˜¦

  4. Thiru permalink
    July 31, 2011 11:00 pm

    Really super…!
    I was spending many hours to add superscript + in my code using unicode. But due to device does not support that, that was failing…
    Finally it works for me…
    Thanks a lot.

  5. January 16, 2012 4:45 am

    This works great, but I also had to add android:minLines=”2″ to the main.xml for the TextView’s entry to prevent the subscript from being cut off.

Leave a comment