Use meta viewport width in Android Webview
Asked Answered
P

1

10

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?

Prudenceprudent answered 30/1, 2014 at 15:29 Comment(0)
P
26

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'/>
Prudenceprudent answered 30/1, 2014 at 15:45 Comment(1)
For some reason this doesn't seem to work for the Marshmallow...any idea?Raggletaggle

© 2022 - 2024 — McMap. All rights reserved.