2013-04-04 103 views
6

当Android平板电脑上的Chrome浏览器(Nexus 7)中显示时,我有一个基本网页,可以正确响应屏幕大小和方向更改(使用CSS媒体查询)。当我在WebView中显示相同的页面时,基于屏幕宽度的媒体查询不起作用。下面是我如何设立的WebView:Android WebView和CSS媒体查询

WebView webView = (WebView) findViewById(R.id.webView); 
webView.getSettings().setJavaScriptEnabled(true); 
webView.getSettings().setLoadWithOverviewMode(true); 
webView.getSettings().setUseWideViewPort(true); 
webView.loadUrl("http://10.0.1.8:8080/cbc/test"); 

的WebView中正确地检测方向的变化,基于以下媒体查询的行为:

@media only screen and (orientation: portrait) { 
    .landscape { display: none; } 
} 

@media only screen and (orientation: landscape) { 
    .portrait { display: none; } 
} 

使用屏幕尺寸不正常工作媒体查询,因为,根据下面的JavaScript,画面宽度和高度通过取向的变化保持恒定:

$("#dimensions").empty(); 
    $("#dimensions").append($("<div>Width: " + screen.width + "</div>")); 
    $("#dimensions").append($("<div>Height: " + screen.height + "</div>")); 
    $("#dimensions").append($("<div>Depth: " + screen.pixelDepth + "</div>")); 

我触发之前的共带有“orientationchange”事件。在Android版Chrome中运行时,宽度和高度值将正确显示,并将设备方向考虑在内。在WebView内部运行时,无论方向如何,宽度和高度都保持不变。

是否有一些配置需要应用于WebView才能获得预期的行为?

回答

-1

当涉及到现代屏幕,你需要指定像素比例。 CSS中的像素是度量值,而不是实际像素。自高分辨率屏幕和视网膜显示以来,像素大小不同。制造商尝试并根据像素大小进行显示,但不适用于媒体查询。你需要做的媒体查询是这样的:

@media 
    only screen and (-webkit-min-device-pixel-ratio: 2), 
    only screen and ( min--moz-device-pixel-ratio: 2), 
    only screen and ( -o-min-device-pixel-ratio: 2/1) { 
     //CSS here 
} 
+1

问题是关系到整个方向变化的跟踪宽度和高度查询。根据像素密度进行选择对此无济于事。 – 2013-08-24 21:55:54

0

尝试在你的JavaScript看着window.innerWidth & window.innerHeight

0

加载HTML后(屏幕更改或任何更改后),您需要WebView CONTENTS的宽度和高度。 是的,但没有getContentWidth方法(只有一个视口值), 和getContentHeight()是不准确的!

答:子类的WebView:

/* 
    Jon Goodwin 
*/ 
package com.example.html2pdf;//your package 

import android.content.Context; 
import android.util.AttributeSet; 
import android.webkit.WebView; 

class CustomWebView extends WebView 
{ 
    public int rawContentWidth = 0;       //unneeded 
    public int rawContentHeight = 0;       //unneeded 
    Context mContext   = null;      //unneeded 

    public CustomWebView(Context context)      //unused constructor 
    { 
     super(context); 
     mContext = this.getContext(); 
    } 

    public CustomWebView(Context context, AttributeSet attrs) //inflate constructor 
    { 
     super(context,attrs); 
     mContext = context; 
    } 

    public int getContentWidth() 
    { 
     int ret = super.computeHorizontalScrollRange();//working after load of page 
     rawContentWidth = ret; 
     return ret; 
    } 

    public int getContentHeight() 
    { 
     int ret = super.computeVerticalScrollRange(); //working after load of page 
     rawContentHeight = ret; 
     return ret; 
    } 
//========= 
}//class 
//=========