本文共 1475 字,大约阅读时间需要 4 分钟。
在Android开发过程中,许多开发者在onCreate方法中直接调用getWidth或getMeasuredWidth来获取控件的宽高,这样会导致获取到的值始终为0。这种现象的原因在于,在onCreate方法执行期间,控件尚未被绘制出来,测量(measure)操作尚未完成。因此,直接在onCreate中获取控件尺寸并不是一个可靠的方法。
针对上述问题,我们可以采用以下三种方法来正确获取控件的宽高信息:
这是一种直接且简单的方法,具体实现如下:
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();
这种方法会触发3次onMeasure()方法,虽然简单,但在实际应用中可能会带来一定的性能开销。
这种方法通过在预绘制阶段获取控件尺寸,具体实现如下:
ViewTreeObserver vto = imageView.getViewTreeObserver();vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { public boolean onPreDraw() { vto.removeOnPreDrawListener(this); int height = imageView.getMeasuredHeight(); int width = imageView.getMeasuredWidth(); return true; }});
这种方法会触发两次onMeasure()方法,相比方法一,性能表现更优。
这种方法在布局完成后获取控件尺寸,具体实现如下:
ViewTreeObserver vto = imageView.getViewTreeObserver();vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { vto.removeGlobalOnLayoutListener(this); int height = imageView.getMeasuredHeight(); int width = imageView.getWidth(); }});
这种方法同样会触发两次onMeasure()方法,与方法二性能表现一致。
在实际项目中,可以根据具体需求选择合适的方法。我们推荐使用方法三,因为它能够避免重复测量,且在布局完成后获取到的尺寸更为稳定。
转载地址:http://cqnwz.baihongyu.com/