Transferred from: http://blog.csdn.net/yangdeli888/article/details/25405263
In OnCreate () using View.getwidth () or view.getheiht () to get the width and height of the view, it seems that there is no problem, actually they go to the value is 0, not the result you want?
What is this for?
When the OnCreate () method is called, the interface is not visible and the memory loading component has not been drawn, and you are unable to get his size.
How can you get the size of the component before you draw it?
Here are three ways to verify:
Method One:
Measurement methods
?
| 12345 |
intwidth =View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);intheight =View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);view.measure(width,height);intheight=view.getMeasuredHeight(); intwidth=view.getMeasuredWidth(); |
Method Two:
?
| 123456789 |
//增加组件绘制之前的监听ViewTreeObserver vto =view.getViewTreeObserver(); vto.addOnPreDrawListener(newViewTreeObserver.OnPreDrawListener() { @Override publicbooleanonPreDraw() { intheight =view.getMeasuredHeight(); intwidth =view.getMeasuredWidth(); }}); |
Method Three:
?
| 12345678910 |
//增加整体布局监听ViewTreeObserver vto = view.getViewTreeObserver(); vto.addOnGlobalLayoutListener(newOnGlobalLayoutListener(){ @Override publicvoidonGlobalLayout() { view.getViewTreeObserver().removeGlobalOnLayoutListener(this); intheight =view.getMeasuredHeight(); intwidth =view.getMeasuredWidth(); } }); |
Then, when the activity enters the runtime, the component's size acquisition method is simple, directly getwidth () and GetHeight ().
Android gets view width and height