在Android Webview中使用元视口宽度

时间:2014-01-30 15:29:57

标签: android android-webview android-browser

我想使用viewport标签将html内容放入WebView。

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

这似乎在Chrome浏览器中运行良好,但无法扩展以适应WebView。我做了一个简化的测试活动:

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);
    }
}

任何人都可以解释原因,或建议修复?

1 个答案:

答案 0 :(得分:16)

好的,你必须使用:

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

但是,如果你像这样设置user-scalable = 0,它就会中断:

    <meta name='viewport' content='width=640, user-scalable=0'/>