How to get width and height of a Webview in android

后端 未结 12 1060
长发绾君心
长发绾君心 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:34

    Here's a more elegant solution

    public void onCreate(Bundle savedInstanceState) {
    
    
            webView = (WebView) findViewById(R.id.webView1);
    
            webView.addOnLayoutChangeListener(new OnLayoutChangeListener() {
    
                @Override
                public void onLayoutChange(View v, int left, int top, int right,int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                     int w= webView.getWidth();
                     int h= webView.getHeight();
    
    
                }
            });
    
    
    
        }   
    
    0 讨论(0)
  • 2021-01-04 17:38

    For anyone else who still struggles. Use these methods to get the height and the width of your webview.

    computeHorizontalScrollRange(); -> for width 
    computeVerticalScrollRange(); -> for height
    
    0 讨论(0)
  • 2021-01-04 17:41

    Hmmm - I looked through the WevView source and I can see that internally they are using View#getWidth and View#getHeight here's one of the WebView's private methods:

    /*
     * Return the width of the view where the content of WebView should render
     * to.
     */
    private int getViewWidth() {
        if (!isVerticalScrollBarEnabled() || mOverlayVerticalScrollbar) {
            return getWidth();
        } else {
            return getWidth() - getVerticalScrollbarWidth();
        }
    }
    

    As noted in the comments you have to make sure you are measuring it after you assign the activity layout e.g. setContentView(R.layout.mylayout);

    0 讨论(0)
  • 2021-01-04 17:41

    If you want to get The Height and Width load time you can't get it because load time can't get it. I suggest to use the webview Touchevent and get the height and width. Otherwise use another view click event and get the height and width.

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

    Use this.

    0 讨论(0)
  • 2021-01-04 17:42

    The onPageFinished call back approach does not work when using loadData or loadDataWithBaseURL. I saw another solution on Andromedev using JavaScript, but I'm not convinced that this is the best path to take.

    0 讨论(0)
  • 2021-01-04 17:42

    You were probably checking for the sizes too soon, most likely in the onCreate. Instead, try this:

    webView.setWebViewClient(new WebViewClient() {
                @Override
                public void onPageFinished(WebView webView, String url) {
                    super.onPageFinished(webView, url);
                    Log.i(TAG, findViewById(R.id.my_component).getWidth(););
                }
            });
    
    0 讨论(0)
提交回复
热议问题