Search code examples
androidandroid-studiowebviewjqmath

Scaling an Android WebView text html to fit?


I have a math equation as a text WebView that I need to fit the entire screen no matter its dimensions.. my first intuition of doing this is simply shrinking the text whenever it gets out of bounds so that it remains constrained, however, I can't find any functions or methods to actually MEASURE the content of that webview, I've tried:

webview.getMeasuredHeight, webview.getHeight

but the issue with them is that they are constantly affixed on the size of the webview widget, not on the content, so I moved to:

webview.getContentHeight

which seemed to work, the problem is it works only after the text is "loaded", so it doesn't get the right answer at first, even if it's called in onPageFinished.

My questions are:

1) Is there a way to know the content size of the TEXTUAL html webview?? I would even appreciate knowing the scroll bar length that would indicate size.

2) Is there a listener function that would enable me to run code from the moment the text actually loaded? The webview declaration looks something like this:

webView = (WebView) findViewById(R.id.webView);
        js = "<html><head>"
                + "<link rel='stylesheet' href='file:///android_asset/mathscribe/jqmath-0.4.3.css'>"
                + "<script src='file:///android_asset/mathscribe/jquery-1.4.3.min.js'></script>"
                + "<script src='file:///android_asset/mathscribe/jqmath-etc-0.4.3.min.js'></script>"
                + "</head><body>"
                + "<script>var s =   '$$" + functext + "$$';M.parseMath(s);document.write(s);</script> </body>";
        webView.loadDataWithBaseURL("", js, "text/html", "UTF-8", "");

The text does not load instantly, so the code relating to it is usually flawed.

3) Is there a webview.getContentWidth or something of the like?


Solution

  • EDIT:

    This code may help you in fitting your wepage to webview.

    webview.getSettings().setLoadWithOverviewMode(true);
    webview.getSettings().setUseWideViewPort(true);
    

    You have to calculate the scale so that content fits on the screen.

    private int getScale()
    {
        Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); 
        int width = display.getWidth(); 
        Double val = new Double(width)/new Double(Your_webpage_width);
        val = val * 100d;
        return val.intValue();
    }
    

    Then use

    WebView web = new WebView(this);
    web.setPadding(0, 0, 0, 0);
    web.setInitialScale(getScale());
    

    2) To run something after webview has completely loaded,just implement WebViewClient and extend onPageFinished() as follows:

    mWebView.setWebViewClient(new WebViewClient() {
    
       public void onPageFinished(WebView view, String url) {
            // do your stuff here
        }
    });