Subscript and Superscript a String in Android

后端 未结 15 1438
面向向阳花
面向向阳花 2020-11-22 09:20

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.

相关标签:
15条回答
  • 2020-11-22 10:01
    ((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>
    
    0 讨论(0)
  • 2020-11-22 10:05

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

    <string name="str">H₂</string>
    
    0 讨论(0)
  • 2020-11-22 10:08

    Example:

    equation = (TextView) findViewById(R.id.textView1);
    SpannableStringBuilder cs = new SpannableStringBuilder("X3 + X2");
    cs.setSpan(new SuperscriptSpan(), 1, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    cs.setSpan(new RelativeSizeSpan(0.75f), 1, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    cs.setSpan(new SuperscriptSpan(), 6, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    cs.setSpan(new RelativeSizeSpan(0.75f), 6, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    equation.setText(cs);
    
    0 讨论(0)
提交回复
热议问题