How To Get Width And Height Of A Webview In Android
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
Solution 1:
Here's a more elegant solution
publicvoidonCreate(Bundle savedInstanceState) {
webView = (WebView) findViewById(R.id.webView1);
webView.addOnLayoutChangeListener(newOnLayoutChangeListener() {
@OverridepublicvoidonLayoutChange(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();
}
});
}
Solution 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.
Solution 3:
You were probably checking for the sizes too soon, most likely in the onCreate
. Instead, try this:
webView.setWebViewClient(newWebViewClient() {
@OverridepublicvoidonPageFinished(WebView webView, String url) {
super.onPageFinished(webView, url);
Log.i(TAG, findViewById(R.id.my_component).getWidth(););
}
});
Solution 4:
For anyone else who still struggles. Use these methods to get the height and the width of your webview.
computeHorizontalScrollRange(); -> for widthcomputeVerticalScrollRange(); -> for height
Solution 5:
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.
*/privateintgetViewWidth() {
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);
Post a Comment for "How To Get Width And Height Of A Webview In Android"