If you want to get width and height before your activity has added it to your view hierarchy, measured it and laid out, you will have to call measure() on the View yourself before calling getMeasuredWidth() or getMeasuredHeight() .
Since the measured width and height are set after calling the measure (which, in turn, calls onMeasure() ), they return 0 to this point. You will need to put MeasureSpec on measure(..) , which will depend on your needs.
MeasureSpec parameters, which allow children to impose any restrictions themselves, look like
int widthMeasureSpec = MeasureSpec.makeMeasureSpec(*some width*, MeasureSpec.EXACTLY); int heightMeasureSpec = MeasureSpec.makeMeasureSpec(*some height*, MeasureSpec.EXACTLY);
The important point . (was changed in the new API) The width specified above can be either explicit px, or ViewGroup.LayoutParams.WRAP_CONTENT or ViewGroup.LayoutParams.FILL_PARENT.
It's also worth noting that when your view is measured in the actual target hierarchy, MeasureSpec, which will be passed to measure() , will be configured based on the ViewGroups layout logic ViewGroups . It can be called more than once if the first vals measures are invalid when viewed in the context of this parent Group view / its own layout restrictions / restrictions of any child sibling view. Without waiting for the viewGroup call measure() , before implementing any logic depending on the measured size, it would be difficult (depending on the situation) to get the final measuredWidth & height from the above solution, but in all cases I used the above method. which was consistent with the goal, but they were relatively simple. If you really need to measure in context, you probably should just do it after onLayout() comes back and explicitly changes any changes, then requestLayout() again.
Dori Dec 06 '11 at 16:53 2011-12-06 16:53
source share