chemistry formula on Android

孤街浪徒 提交于 2020-01-11 19:59:21

问题


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);


回答1:


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.




回答2:


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"/>

Hope this helps someone.




回答3:


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.



来源:https://stackoverflow.com/questions/23428302/chemistry-formula-on-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!