How get webview scale in Android 4

2019-04-25 09:45发布

问题:

WebView.getScale() is deprecated (but still usable)

The recommended way to get scale for webview is to use WebViewClient.onScaleChanged() http://developer.android.com/reference/android/webkit/WebViewClient.html#onScaleChanged(android.webkit.WebView, float, float)

I've added corresponding handler in my custom webview:

public class CustomWebView extends WebView {

public CustomWebView(Context context) {
    super(context);
    setWebViewClient(new WebViewClient() {
        @Override
        public void onScaleChanged(WebView view, float oldScale, float newScale) {
            super.onScaleChanged(view, oldScale, newScale);
            currentScale = newScale
        }
    });
}

And now the problem: the method not invoked (at least on my nexus 7) if I'm zoom in/zoom out using pinch, so it works good only if I use zoom controls button.

回答1:

I'm developing for API level 17 and I ended up using the deprecated method getScale() for the same reason. WebViewClient.onScaleChanged() simply wasn't triggered when I changed the scale using pinch zoom in the WebView. I have a custom GestureListener in my extended WebView that behaves differently when the view is zoomed in (scale 1.0+). I couldn't reliably get the proper scale value when I set a class variable in onScaleChanged().



回答2:

try :

public MyWebView(Context context, AttributeSet attrs) {
    super(context, attrs);
    // TODO Auto-generated constructor stub
    setWebViewClient(new WebViewClient() {
        @Override
        public void onScaleChanged(WebView view, float oldScale, float newScale) {
            super.onScaleChanged(view, oldScale, newScale);
            currentScale = newScale;
        }
    });
}