Display Good-looking Math Formula in Android

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="https://stackoverflow.com/questions/17029780/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.

Leave a Comment