在oncreate()中利用view.getWidth()或是view.getHeiht()来获取view的宽和高,看似没有问题,其实它们获取到的值是0,并不是你想要的结果。这是为什么呢?因为,在调用oncreate()方法时,界面处于不可见状态,需要加载的组件还没有绘制出来,这时你是无法获取它的尺寸的。
那如何在绘制组件之前能获取到该组件的尺寸大小呢?
方法1
//测量
int width =View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
int height =View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
view.measure(width,height);
int height=view.getMeasuredHeight();
int width=view.getMeasuredWidth();
方法2
//组件绘制前监听
ViewTreeObserver vto =view.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
int height =view.getMeasuredHeight();
int width =view.getMeasuredWidth();
}
});
方法3
//监听整个布局
ViewTreeObserver vto = view.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener(){
@Override
public void onGlobalLayout() {
view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
int height =view.getMeasuredHeight();
int width =view.getMeasuredWidth();
}
});