Question

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

Was it helpful?

Solution

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.

OTHER TIPS

I had a similar problem to solve. I created a simple library by extending WebView and using JavaScript in the background. https://github.com/RanaRanvijaySingh/EquationView

String strChem = "Chemistry: \\(\\ce{CO2 + C -> 2 CO}\\)";
EquationView equationViewChem = findViewById(R.id.equationViewChem);
equationViewChem.setText(strChem);

In your layout file:

<com.rana.equationview.EquationView
 android:id="@+id/equationViewChem"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"/>

enter image description here

Hope this helps someone.

I think you have found a solution that fits you. Perhaps, if there is a rule to know when a symbol will be a subscript or superscript, or the spansize you have to use, you can write a method to parse a given a formula privided as a string and automatically provide the formated html output.

To do this, and assuming there are specific rules, you can use a finite state machine that will "compile" a text string to the html output you need.

If you are looking for something like this let me know and we may be able to work it out.

Another option would be to see if you find (in Internet) a font that meets your needs (Or perhaps build your own). You can import a font putting the font file in the assets folder and setting it from there in the source.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top