Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display Good-looking Math Formula in Android

People also ask

How do you display math formulas and apps in Android?

Although there is no direct way to show math formula in android TextView, But you can use MathJaxWebView and use the webview to show formula using it. Visit the link for more infomation on how to do it. Show activity on this post. *You can use MathJax also but it is slightly heavy.

What is the most beautiful math formula?

Euler's identity is an equality found in mathematics that has been compared to a Shakespearean sonnet and described as "the most beautiful equation." It is a special case of a foundational equation in complex arithmetic called Euler's Formula, which the late great physicist Richard Feynman called in his lectures (opens ...


If I understand your problem correctly, it seems the issue is due to the MathJax library has not completed loading (from the loadDataWithBaseURL() call) when you call the additional loadUrl()s to display the formula. The simplest fix is to wait for the onPageFinished() callback to make the call.

For example, the following code seems to work fine on mine:

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    final WebView w = (WebView) findViewById(R.id.webview);
    w.getSettings().setJavaScriptEnabled(true);
    w.getSettings().setBuiltInZoomControls(true);
    w.loadDataWithBaseURL("http://bar", "<script type='text/x-mathjax-config'>" 
            + "MathJax.Hub.Config({ "
            + "showMathMenu: false, " 
            + "jax: ['input/TeX','output/HTML-CSS'], " 
            + "extensions: ['tex2jax.js'], "
            + "TeX: { extensions: ['AMSmath.js','AMSsymbols.js'," 
            + "'noErrors.js','noUndefined.js'] } "
            + "});</script>" 
            + "<script type='text/javascript' " 
            + "src='file:///android_asset/MathJax/MathJax.js'"
            + "></script><span id='math'></span>", "text/html", "utf-8", "");
    w.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (!url.startsWith("http://bar")) return;
            w.loadUrl("javascript:document.getElementById('math').innerHTML='\\\\["
                    + doubleEscapeTeX("sample string") + "\\\\]';");
            w.loadUrl("javascript:MathJax.Hub.Queue(['Typeset',MathJax.Hub]);");
        }
    });
}

Update: To accommodate additional output in the WebView, I would suggest adding HTML elements to the initial loadDataWithBaseURL() call. So for the example above, instead of this line at the end:

            + "></script><span id='math'></span>", "text/html", "utf-8", "");

We can do something like the following:

            + "></script><span id='text'>Formula:</span>"
            + "<span id='math'></span>", "text/html", "utf-8", "");

Additionally, if you need to update that part interactively afterward, you can use the same mechanism that we used for the "math" part, something like:

            w.loadUrl("javascript:document.getElementById('text').innerHTML='"
                    + newText + "';");

You can also use other HTML elements (instead of the <span> that we use above) if you want to have specific styling/formatting.


Instead of using javascript and javascript libraries to render the LaTeX client-side, why not do the following?

  1. Write a server-side function that takes some LaTeX string and produces an image file. You can do this with the "out of the box" standard LaTeX command line tool. (It seems like this is something you're capable of doing, and that the problem is in getting the rendering to take place client-side.)

  2. Create an endpoint on your web site/service that looks like the following:
    GET /latex?f={image format}&s={latex string}

  3. On your web pages, use a simple HTML <img/> tag to render your LaTeX. For example:
    <img src="/latex?f=jpeg&s=f%40x%41%61x%942"/>
    will render the f(x)=x^2 equation as a JPEG.

  4. (optional) Create a simple server-side cache for (f,s) pairs so that you only render a particular LaTeX string on the first request ever made for that particular string (by any client). As a first prototype, you could just have a server directory in which you have files named {hash(s)}.{f}, where hash is just some hash function like SHA1.

This relieves you from trying to make everything work client-side with javascript. And, I would argue (although some may disagree), that this is a lot cleaner. All you're sending to the client is:

  1. the HTML <img/> tag
  2. the actual image contents when the browser resolves the src attribute

Very lightweight and fast!


The "capital A" problem is a konwn bug of MathJax on Android WebView. You can replace the font files with tweaked font files. The fix will work when using HTML-CSS output with TeX-fonts. Besides MathJax, you can try KaTeX, which is less beautiful but faster.

Actually I've packed them both into an Android custom view, have a look on MathView.


Late to the party but I think I have a better solution than Joe's. The original question asked:

how can I show plain text in paragraph and a formatted equation within the same webview?

In the original example we had:

w.loadUrl("javascript:document.getElementById('math').innerHTML='\\\\["
                  +doubleEscapeTeX("sample string")
                  +"\\\\]';");

Do you notice the \\\\[ and \\\\]? Those four backslashes are interpreted by LaTeX as only one, and \[ and \] in LaTeX is a shorthand for \begin{equation}... \end{equation} which produces a block of displayed mathematics. If we want a paragraph of text with some equations within the paragraph we need to get rid of the \\\\[ and use the LaTeX command \( and \). The code for an example with paragraph mathematics and displayed mathematics would be:

w.loadUrl("javascript:document.getElementById('math').innerHTML='"
   +doubleEscapeTeX(
           "This is a second degree equation \\( \\small ax^2+bx+c=0\\) and its "
          +"roots are \\[x=\\frac{-b\\pm \\sqrt{b^2-4ac}}{2a}. \\]"
    )+"';");

The WebView becomes: enter image description here Notes:

  • We only need two backslashes instead of four, this is because we are inside doubleEscapeTeX() and this function duplicates the backslashes.

  • Also the text outside the math environments is rendered with HTML (inside the <span id='math'> tag).

  • The LaTeX font is bigger that the html font, so adding a \\small in each math environment will make them roughly the same size. Here I added the \\small command only to the first equation to show the difference.