strings95 strings95 - 6 months ago 27
Android Question

chemistry formula on Android

I'm developing an android project and I want to render some chemistry formula.

I wrote the following code and I got the following result.

I create a custom string and show it in a textview.

But my question is this: Is this the best way to do this? And is there another way to handle that?

str = new SpannableString(Html.fromHtml("2H<sup>+</sup> + So<sub size = 2>4</sub><sup size = 2>2-</sup> --> H<sub size =2>2</sub>So<sub size = 2>4</sub>"));
ss1.setSpan(new RelativeSizeSpan(0.6f), 2,3, 0); // set size
ss1.setSpan(new RelativeSizeSpan(0.6f), 8,11, 0); // set size
ss1.setSpan(new RelativeSizeSpan(0.6f), 17,18, 0); // set size
ss1.setSpan(new RelativeSizeSpan(0.6f), 20,21, 0); // set size
TempF.setText(ss1,TextView.BufferType.SPANNABLE);


Example Chemical Formula

Answer

I don't think there is a better way.

Unfortunately Html.fromHtml() ignores <font size="n"> tags, so these spans need to be added manually, as you have done.

Comments