onCreate onStart onResume都不能直接获得View的宽度高度,因为View的绘制并不是和Activity的生命周期同步进行的。
解决方法:
1、
onWindowFocusChanged
当Activity失去获得焦点的时候,说明View已经绘制完了,因此可以获得宽度高度。
e.g.
public void onWindowFocusChanged(boolean hasFocus){
super.onWindowFocusChanged(hasFocus);
if(hasFocus){
int width = view.getMeasuredWidth();
int height = view.getMeasuredHegiht();
}
}
2、
view.post(runnable)
post可以将runnable投递到消息队列的尾部,然后等待Looper调用runnable的时候,view已经初始化好了。
e.g.
protected void onStart(){
super.onStart();
view.post(new Runnable(){
public void run(){
int width = view.getMeasuredWidth();
int height = view.getMeasuredHegiht();
}
});
}
3、
ViewTreeObserver
View树的状态或者可见性发生改变的时候回回调onGlobalLayout方法,因此是获得View的高宽度的好时机。
e.g.
protected void onStart(){
super.onStart();
ViewTreeObserver observer = view.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener(){
public void onGlobalLayout(){
view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
int width = view.getMeasuredWidth();
int height = view.getMeasuredHegiht();
}
});
}