Android webview fit all content to screen

MW_hk picture MW_hk · Apr 9, 2013 · Viewed 12.2k times · Source

Hi I have a webview and I want it to fit to screen, such that the user does not have to scroll horizontally or vertically

I have searched before, many suggest the following but it only limits the width, user will still have to scroll vertically:

engine = (WebView) (findViewById(R.id.webView1));
engine.loadUrl(www.example.com); 
engine.getSettings().setLoadWithOverviewMode(true);
engine.getSettings().setUseWideViewPort(true);

I tried another method, using scaling method, but it won't work..... I got the window width (1024 pixels) and the web content width was also 1024 pixels!! So the scaling did not work.... Is there any method to get the correct scale?

Or....is there any other way?....THANKS!!

// get the window width and height
    Point outSize = new Point();
    getWindowManager().getDefaultDisplay().getSize(outSize);
    width = outSize.x;
    height = outSize.y;
    Log.i("Menuboard", "width: " + Integer.toString(width) + ", height: "
            + Integer.toString(height));

WebViewClient client = new WebViewClient() {

        public void onPageFinished(WebView view, String url) {
            int x = engine.getWidth();
            int y = engine.getHeight();

            Log.i("Menuboard", "web width: " + Integer.toString(x)
                    + ", height: " + Integer.toString(y));

            int scale1 = width * 100/x;
            int scale2 = height * 100/y;

            Log.i("Menuboard", "Scale1: " + Integer.toString(scale1)
                    + ", Scale2: " + Integer.toString(scale2));

            if (scale1 < scale2) {
                engine.setInitialScale(scale1);
                Log.i("Menuboard", "scale1");
            } else if (scale1 > scale2) {
                engine.setInitialScale(scale2);
                Log.i("Menuboard", "scale2: " + Integer.toString(scale2));
            }
        }
    };

    engine = (WebView) (findViewById(R.id.webView1));
    engine.loadUrl(string);
    engine.getSettings().setBuiltInZoomControls(true);
    engine.setPadding(0, 0, 0, 0);
            engine.setWebViewClient(client);

Just some notes:

To scale the webview:

engine = (WebView) (findViewById(R.id.webView1));
engine.loadUrl(www.example.com);
engine.getSettings().setBuiltInZoomControls(true);
engine.setPadding(0, 0, 0, 0);
engine.setInitialScale(50); // 0 - 100 where 100 is full scale

To get window width and height:

Point outSize = new Point();
getWindowManager().getDefaultDisplay().getSize(outSize);
width = outSize.x;
height = outSize.y;

Answer

Drw picture Drw · Jun 5, 2015

use this following methods.

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