webview页面随设备分辨率缩放

android客户端常会调用到html页面,给webview页面适配android凌乱的设备带来很大的困难。

可以找到的方法是通过ZoomDensity.setDefaultZoom根据分辨率480宽度为基准缩放。

不过ZoomDensity.setDefaultZoom在2.0以下的平台是无法调用的,需要自己反射调用。

即使是ZoomDensity.setDefaultZoom设置了缩放,但还是会在很多设备无效。经过摸索还需做一些修改:

1,页面head添加

     <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />

 

2,设置字体也按480基准缩放。

下面是代码:

    private void setZoom(WebSettings webSettings) {
	int screenDensity = getResources().getDisplayMetrics().densityDpi;
	String zd = "FAR";
	switch (screenDensity) {
	case DisplayMetrics.DENSITY_LOW:
	    zd = "CLOSE";
	    break;

	case DisplayMetrics.DENSITY_MEDIUM:
	    zd = "MEDIUM";
	    break;
	}
	Class<?> zoomDensityClass = null;
	Enum<?> zoomDensity = null;

	try {
	    if (zoomDensityClass == null) {
		zoomDensityClass = Class.forName("android.webkit.WebSettings$ZoomDensity");
	    }
	    if (zoomDensity == null) {
		zoomDensity = (Enum<?>) Enum.valueOf((Class) zoomDensityClass,zd);
	    }

	    Method method = WebSettings.class.getDeclaredMethod( "setDefaultZoom", new Class<?>[] { zoomDensityClass });
	    if(method!=null){
		method.invoke(webSettings, zoomDensity);
	    }
	    
	    method = WebSettings.class.getDeclaredMethod( "setTextZoom", new Class<?>[] { int.class });
	    if(method!=null){
		method.invoke(webSettings, 100 * getWindowManager().getDefaultDisplay().getWidth() / 480);
	    }
	} catch (Exception e) {
	    Log.e(TAG, e.getMessage());
	    return;
	}
    }
 

猜你喜欢

转载自obacow.iteye.com/blog/1740511