Android: View.measure(int,int) always wants to be

2019-05-30 01:12发布

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

2条回答
我想做一个坏孩纸
2楼-- · 2019-05-30 01:44

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.

查看更多
可以哭但决不认输i
3楼-- · 2019-05-30 01:47

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.

查看更多
登录 后发表回答