How to get width and height of a Webview in android

后端 未结 12 1125
长发绾君心
长发绾君心 2021-01-04 17:13

I want to determine the width and the height of the WebView. I have already tried it using:

webView.getWidth();
webView.getHeight();
         


        
12条回答
  •  春和景丽
    2021-01-04 17:52

    You need the width and height of the WebView CONTENTS, after you loaded your HTML. YES you do, but there is no getContentWidth method (only a view port value), AND the getContentHeight() is inaccurate !

    Answer: sub-class 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
    //=========
    

提交回复
热议问题