views:

56

answers:

2

Hi guys,

I have a WebView that I've added to a view group:

webView = new WebView(context);
addView(webView, ViewGroup.LayoutParams.WRAP_CONTENT);

This lives in my viewgroup's constructor.

Then on layout, I want to do this:

webView.measure(View.MeasureSpec.makeMeasureSpec(getWidth(),View.MeasureSpec.EXACTLY),  
                View.MeasureSpec.makeMeasureSpec(3000, View.MeasureSpec.AT_MOST));

Unfortunately, unless I specify EXACTLY, the webView.getMeasuredHeight() always returns 0. What I want to do, is determine how big the webview wants to be so that I can lay other elements around it. I specified that I want the webview to be big enough to encompass it's content and I provided generous amount of space. So why is it still 0?

Thanks

Update 1

By the time webView gets measure() request, it should know how much data it has, no?

webView = new WebView(context);
webView.loadData("<html></html>","text/html", "utf-8");
addView(webView, new ViewGroup.LayoutParams(getWidth(), 1000));
+1  A: 

My guess is that you're measuring the view in onCreate(). The view isn't drawn yet. You have to wait until a time after the view is drawn before you can measure it.

Falmarri
Maybe my approach isn't right. I need to know how big the view is before I can draw, it no?
EightyEight
How exactly are you drawing it and where? Why don't you just use wrap_content?
Falmarri
I have a callback that's attached to a button. The callback sets the visibility of webview to VISIBLE, then calls webView.measure(), then calls webView.layout(). I'm not sure what wrap_content is.
EightyEight
You need to post some more code then. This is a pretty non standard way to draw a view.
Falmarri
+2  A: 

This:

addView(webView, ViewGroup.LayoutParams.WRAP_CONTENT);

is very wrong. The second parameter, when passed as an int, is the index of the view inside the parent. This does not do what you think it does. You should pass a new instance of LayoutParams instead.

Your problem is probably that you do a measurement before the WebView had time to load the HTML document. You measure with the constraint AT_MOST 3000, and 0 definitely respects that constraints. WebView is just telling you that its content has a height of 0 for now.

Romain Guy
Oh, wow. You're totally right. I updated code above, with no difference.
EightyEight
I don't think loadData() is synchronous. You need to wait until WebView has finished parsing the data and built the DOM. There must be a listener for this.
Romain Guy
For future googlers; WebView dispatches an event to a PictureListener when it has finished laying itself out.
EightyEight