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 →
Great solution! I’ve been looking for this. My superscript text was cutoff in a Spinner element.
for some reason this solution doesn’t appear to work for strings that are used as listview titles (textviews).. At least in my case
It creates the superscript but doesn’t make it small… even after adding tag đŸ˜¦
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.
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.