I want to determine the width and the height of the WebView
. I have already tried it using:
webView.getWidth();
webView.getHeight();
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();
}
});
}
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
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);
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.
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.
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(););
}
});