Question

I would like to use the viewport tag to fit html content into a WebView.

<meta name='viewport' content='width=640'/>

This seems to work fine in Chrome browser, but does not scale to fit in the WebView. I made a simplified test activity:

public class MyActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //--------------------------------------------------
        // Create a simple html page including viewport tag.
        //--------------------------------------------------

        String html = "<!DOCTYPE html>" +
                "<html>" +
                "<head>" +
                "<meta name='viewport' content='width=640'/>" +
                "<title>Viewport Test</title>" +
                "</head>" +
                "<body style=\"margin: 0px;\">" +
                "<div style=\"width: 600px; height: 600px; border: 20px solid green; background-color: red;\"></div>" +
                "</body>" +
                "</html>";

        //-----------------------------------
        // Place html in WebView.
        //-----------------------------------

        WebView webView = new WebView(this);

        webView.loadData(html, "text/html", "utf-8");

        setContentView(webView);

        //-----------------------------------
        // Launch Chrome with the same html.
        //-----------------------------------

        Intent intent = new Intent(Intent.ACTION_VIEW);

        intent.setComponent(ComponentName.unflattenFromString("com.android.chrome/com.android.chrome.Main"));

        intent.setData(Uri.parse("data:text/html;charset=utf-8;base64," + Base64.encodeToString(html.getBytes(), Base64.NO_WRAP)));

        startActivity(intent);
    }
}

Can anyone explain why, or suggest a fix?

Was it helpful?

Solution

OK, you have to use:

    WebSettings settings = webView.getSettings();
    settings.setLoadWithOverviewMode(true);
    settings.setUseWideViewPort(true);

But also, it breaks if you set user-scalable=0 like this:

    <meta name='viewport' content='width=640, user-scalable=0'/>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top