androidtextviewformatsuperscriptspanned

Android Formatting Superscript and Subscript


I have an array of Strings that I want to display within a proper format for my TextViews. I have already looked at using the Html.fromHtml() approach as posted here but I still can't figure out my specific solution.

The issue that I encounter is I am not sure how to format just a portion of the string. The "^" char should be a super script and the "_" underscore should be a subscript. Anything within brackets "{}" means that the superscript/subscript should apply to everything within it.

For example: The string ^2S_{1/2} should be displayed as: 2S1/2

Another example: 1s^2 should be formatted within a textview to appear as such: 1S2

I have been stumped for the past couple hours. All help is appreciated. Thank you!


Solution

  • For your example to format this ^2S_{1/2}, you will write your string value as

    "<sup><small>2</small></sup> S <sub><small>½</small></sub>".

    And write symbols in their codes and also use Html.fromHtml() in your TextView setText() method.