How can you print a string with a subscript or superscript? Can you do this without an external library? I want this to display in a TextView in Android.
How can you print a string with a subscript or superscript? Can you do this without an external library? I want this to display in a TextView in Android.
For "a" copy and paste this "ᵃ"
You can copy and paste any of these Superscripts and Subscripts directly into your Android String Resource.
Example:
<string name="word_with_superscript" translatable="false">Trademark ᵀᴹ</string>
Result:Trademark ᵀᴹ
Superscript and Subscript letters
Superscript capital ᴬ ᴮ ᴰ ᴱ ᴳ ᴴ ᴵ ᴶ ᴷ ᴸ ᴹ ᴺ ᴼ ᴾ ᴿ ᵀ ᵁ ⱽ ᵂ
Superscript minuscule ᵃ ᵇ ᶜ ᵈ ᵉ ᶠ ᵍ ʰ ⁱ ʲ ᵏ ˡ ᵐ ⁿ ᵒ ᵖ ʳ ˢ ᵗ ᵘ ᵛ ʷ ˣ ʸ ᶻ
Subscript minuscule ₐ ₑ ₕ ᵢ ⱼ ₖ ₗ ₘ ₙ ₒ ₚ ᵣ ₛ ₜ ᵤ ᵥ ₓ
The HTML.fromHTML(String) was deprecated as of API 24. They say to use this one instead, which supports flags as a parameter. So to go off of the accepted answer:
TextView textView = ((TextView)findViewById(R.id.text));
textView.setText(Html.fromHtml("X<sup>2</sup>", Html.FROM_HTML_MODE_LEGACY));
And if you want code that considers pre-24 API's as well:
TextView textView = ((TextView)findViewById(R.id.text));
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
textView.setText(Html.fromHtml("X<sup>2</sup>", Html.FROM_HTML_MODE_LEGACY));
} else {
textView.setText(Html.fromHtml("X<sup>2</sup>"));
}
This answer was derived from: https://stackoverflow.com/a/37905107/4998704
The flags and other documentation can be found here: https://developer.android.com/reference/android/text/Html.html
Based on Gerardo's answer here I created this extension on Int
fun Int.toSuperScript(): String {
return when (this) {
0 -> "\u2070"
1 -> "\u00B9"
2 -> "\u00B2"
3 -> "\u00B3"
4 -> "\u2074"
5 -> "\u2075"
6 -> "\u2076"
7 -> "\u2077"
8 -> "\u2078"
9 -> "\u2079"
else -> ""
}
}