Android 获取 View 尺寸的三种常见方案
在 Android 开发中,有时候我们需要拿到某个 View 的实际宽高。比如在设置背景图或者做动画计算时。但如果你直接在 onCreate 里调用 getWidth() 或 getHeight(),大概率是 0。这是因为此时 View 还没有经历完整的测量和布局阶段。
方案一:手动触发测量
如果还没进入布局流程,我们可以手动模拟一次测量过程。关键在于使用 UNSPECIFIED 模式,让系统根据内容决定大小。
int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
imageView.measure(w, h);
int height = imageView.getMeasuredHeight();
int width = imageView.getMeasuredWidth();
textView.append("\n" + height + "," + width);
注意,这行代码通常放在 setContentView 之后立即执行。这里有个细节,MeasureSpec 的第二个参数决定了测量的约束条件,用 UNSPECIFIED 表示不限制,View 会按自身内容显示。
方案二:OnPreDraw 监听
当 View 已经完成了测量和布局,但还没开始绘制时,这是一个很好的时机。这时候的尺寸已经是最终的了。
ViewTreeObserver vto = imageView.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
int height = imageView.getMeasuredHeight();
int width = imageView.getMeasuredWidth();
textView.append("\n" + height + + width);
;
}
});

