简体   繁体   中英

How to retrieve width and heigh of the webview in Cordova Android?

I write a Cordova plugin for Android.

Here is a simple initialization function which resume mu probleme

public class MyPlugin extends CordovaPlugin {

  CordovaWebView _webView;
  ViewGroup _root;

  public void initialize(CordovaInterface cordova, final CordovaWebView webView) {
    super.initialize(cordova, webView);

    _webView = webView;
    _root = (ViewGroup) _webView.getView().getParent();

    Log.d(TAG, Integer.toString(root.getLayoutParams().width)); // -1
    Log.d(TAG, Integer.toString(webView.getView().getLayoutParams().width)); //-1 too
  }

  public boolean execute(final String action, final CordovaArgs args, final CallbackContext _callbackContext) throws JSONException {
    Log.d(TAG, Integer.toString(_root.getLayoutParams().width)); // -1
    Log.d(TAG, Integer.toString(_webView.getView().getLayoutParams().width)); // -1
    ...
  }
}

Note that when logging FrameLayout.LayoutParams.MATCH_PARENT it displays -1 . Does the default WebView layout is set with MATCH_PARENT in Cordova?

How I could retrieve the WebView or the parent of the WebView with/heigh ?

After page rendering get finished you can get that event in onPageFinished method of WebView client. In that method you can use

webview.getContentWidth() and webview.getContentHeight()

for getting content's height and width of webpage.

Note:- This approach is for the android stock webview. Hoping it will work for cordova webview.

I was using the wrong method. getLayoutParams() does not give the actual dimensions.

My code work in both initialize and execute function with:

Log.d(TAG, Integer.toString(_webView.getView().getWidth()));
Log.d(TAG, Integer.toString(_webView.getView().getHeight()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM