Subscript and Superscript a String in Android

2018-12-31 13:51发布

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.

13条回答
只靠听说
2楼-- · 2018-12-31 14:15

If you want to set the superscript from string.xml file try this:

string resource:

<string name="test_string">X&lt;sup&gt;3&lt;/sup&gt;</string>

if you want the superscript to be smaller:

<string name="test_string">X&lt;sup&gt;&lt;small&gt;3&lt;/small&gt;&lt;/sup&gt;</string>

Code:

textView.setText(Html.fromHtml("Anything you want to put here"+getString(R.string.test_string)));
查看更多
春风洒进眼中
3楼-- · 2018-12-31 14:15

I found this article on how to use a Spannable or in a string resource file: <sup> or <sub> for superscript and subscript, respectively.

查看更多
只若初见
4楼-- · 2018-12-31 14:16
yourTextView.setText(Html.fromHtml("X<sup>2</sup>"));

This will be the result in you yourTextView =

X2

查看更多
后来的你喜欢了谁
5楼-- · 2018-12-31 14:17

It bit late but following just work fine, use superscript as special character, I used spacial char here.

<string name="str">H₂</string>
查看更多
冷夜・残月
6楼-- · 2018-12-31 14:17

In the code just put this "\u00B2" Like this:

textView.setText("X\u00B2");

查看更多
临风纵饮
7楼-- · 2018-12-31 14:19
((TextView)findViewById(R.id.text)).setText(Html.fromHtml("X<sup><small>2</small></sup>")); 

(or) From String Resource File:

<string name="test_string">
  <![CDATA[ X<sup><small>2</small></sup> ]]>
</string>
查看更多
登录 后发表回答