这些方法在动态检索时返回正确的值,例如。在 onCreate() 中,但唯一的异常(exception)是当维度在 xml 布局文件中指定为 undefined 时, 像 'wrap content' 等。有没有办法检索这些值???
最佳答案
这应该返回正确的宽度和高度。 onCreate 在 subview 的布局完成之前被调用。所以宽度和高度还没有计算出来。获取高度和宽度。把它放在 onCreate 方法上
LinearLayout layout = (LinearLayout)findViewById(R.id.YOUD VIEW ID);
ViewTreeObserver vto = layout.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
hs.getViewTreeObserver().removeGlobalOnLayoutListener(this);
int width = layout.getMeasuredWidth();
int height = layout.getMeasuredHeight();
}
});
关于Android 布局参数 getWidth() getHeight(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7694641/