Android - 在View显示前获取其高度和宽度
Android开发经常需要在Activity显示前获取某个View的高度和宽度,例如:程序需要在onCreate()方法中得到一个View的高度和宽度,或者需要知道一个Visibility为Gone的View的高度和宽度
。此时如果直接调用View
的getWidth()和getHeight()方法,得到的结果是0。
原因是在上述情况中,View并没有实际绘制,既然原因找到了,解决办法也就有了,我们可以
调用View.measure()方法,之后在获取View.getMeasuredWidth()和View.getMeasuredHeight()。
Display display = getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); view.measure(size.x, size.y); int width = view.getMeasuredWidth(); int height = view.getMeasuredHeight();