How to write a chemical formula with upper and lower characters in TextView ?

As an example - how to derive such a formula: enter image description here

    1 answer 1

    For example, using HTML tags:

    • Superscript: <sup>upper</sup> ;
    • Subscript: <sub>lower</sub> ;

     String s = "<sup>upper</sup><sub>lower</sub>"; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) { mTextView.setText(Html.fromHtml(s, Html.FROM_HTML_MODE_LEGACY)); } else { mTextView.setText(Html.fromHtml(s)); } 

    Alternatively, you can use SpannableStringBuilder :

     SpannableStringBuilder ssb = new SpannableStringBuilder("Cu+6"); ssb.setSpan(new SuperscriptSpan(), 2, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); ssb.setSpan(new RelativeSizeSpan(0.75f), 2, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); ssb.setSpan(new SubscriptSpan(), 3, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); ssb.setSpan(new RelativeSizeSpan(0.75f), 3, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); mTextView.setText(ssb); 

    UPD: In the line that is stored in the resources, it is necessary to replace < with &lt; ( less-than sign ), > on &gt; ( greater-than sign ):

     <string name="str">&lt;sup&gt;upper&lt;/sup&gt;&lt;sub>lower&lt;/sub&gt;</string> 
    • and in the strings.xml file how to make a record, what to use as a resource? - Maxim Fomichev
    • @MaksimFomichev, Updated the answer. - post_zeew
    • thank you very much! - Maxim Fomichev