How to get width and height of a Webview in android
Asked Answered
U

12

11

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

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

but the resulting log always shows them to be 0.

Until answered 23/10, 2009 at 10:39 Comment(2)
Can you post your code? Remember you cannot get the width and height of a view in the OnCreate method because the layout hasn't occurred yet.Clementia
i put my code is here height=mainWebView.getHeight(); System.err.println("Display Total Height-->"+ mainWebView.getHeight()); System.err.println("Measure Height-->"+mainWebView.getMeasuredHeight());Verso
K
6

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();


            }
        });



    }   
Kindness answered 20/3, 2014 at 16:41 Comment(0)
S
2

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(););
            }
        });
Signature answered 19/12, 2010 at 1:48 Comment(0)
G
2

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.

Gratia answered 24/4, 2012 at 2:40 Comment(0)
W
2

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
Wigley answered 16/8, 2013 at 9:10 Comment(2)
Note that these may return different values to getWidth() and getHeight() as they return the entire scrollable width/height rather than the actual widht/height of the webview on screen.Carpentry
Also note that these methods are protected and you might find it difficult to use them from inside your custom layout for example.Sirdar
S
1

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);

Sst answered 23/10, 2009 at 18:3 Comment(0)
R
1

you are checking size of webview too early. you can try this in following method

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    // TODO Auto-generated method stub
    super.onWindowFocusChanged(hasFocus);
            webView.getWidth();
            webView.getHeight();
}
Ralf answered 31/7, 2013 at 11:1 Comment(0)
C
1

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
//=========
Charpoy answered 24/7, 2016 at 19:23 Comment(0)
V
1

I used a work-around , instead of fetching from unreliable webview get from DisplayMetrics, assuming you have webview width almost equal to phone screen size and height almost equal to height of phone screensize.

DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int height = (int) displayMetrics.heightPixels*0.9;
int width = displayMetrics.widthPixels;
Vacuum answered 4/1, 2019 at 22:7 Comment(0)
V
0

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.

Verso answered 16/8, 2012 at 7:27 Comment(0)
M
0

I had the same problem. I just put initWebView method in onWindowFocusChangedt.

public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    initWebView();
}


private void initWebView(){
    if(isOnline()){
        venueWebView = (WebView) findViewById(R.id.venueWebView);
        String url = "some url";
        int viewWight = venueWebView.getWidth();
        int viewHeight = venueWebView.getHeight();
        venueWebView.loadUrl(url);
    }
Memphis answered 14/11, 2014 at 16:55 Comment(0)
Y
0

I hope my answer helps somebody.

If you want to get height of webview after content is loaded then this could be helpful.

ViewTreeObserver viewTreeObserver  = mWebView.getViewTreeObserver();
viewTreeObserver.addOnPreDrawListener(new OnPreDrawListener() {
 @Override
 public boolean onPreDraw() {                                
     int height = mWebView.getMeasuredHeight();
        if( height != 0 ){
      Toast.makeText(getActivity(),"height:"+height,Toast.LENGTH_SHORT).show();
                             mWebView.getViewTreeObserver().removeOnPreDrawListener(this);
                       }
                       return false;
               }
       });
Yarbrough answered 21/3, 2015 at 14:17 Comment(0)
G
0

If you want to get the original height after loading content, you can use the below code. Though the code is deprecated, yet it works perfectly.

webview.setPictureListener(new WebView.PictureListener() {
        @Override
        public void onNewPicture(WebView webView, @Nullable Picture picture) {
            int height = webview.getContentHeight();
            int height1 = webview.getMeasuredHeight();
            int height2 = webview.getHeight();
        }
    });
Gord answered 12/12, 2019 at 11:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.