Elye Elye - 1 year ago 118
Android Question

Manually measuring layout before used in recyclerview

I wanted to measure the height of some layouts ahead of them before used (in recyclerview). All the layout either have wrap_content size or specific dp set on it (i.e. not dependent on the parent view).

I made a function as below.
It works well for layout that is purely wrap_content size, and doesn't have any layout within that has defined size (i.e. all wrap_content)

private float measureViewHeight(int resource) {
View view = getLayoutInflater(null).inflate(resource, null);
view.measure(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
return (float) view.getMeasuredHeight();

But if the layout is containing some layouts that has specific dp height defined, the measurement return is not inaccurate. How should I fix my function so it returns the right value?

Answer Source

The parameters of View.measure have special meaning and you should call MeasureSpec.makeMeasureSpec to get the parameter.


view.measure(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);


view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download