Use view in oncreate. getWidth () or view. getHeiht () is used to obtain the width and height of the view. It seems that there is no problem. In fact, the value they get is 0, which is not the result you want?
Why?
When the oncreate () method is called, the interface is invisible and the memory-loaded component has not been drawn. You cannot obtain its size.
So how can we get the size of the component before drawing it?
There are three methods, verified:
Method 1 :
// Measurement Method
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();
Method 2 :
// Add the listener ViewTreeObserver vto = view before the component is drawn. getViewTreeObserver (); vto. addOnPreDrawListener (new ViewTreeObserver. onPreDrawListener () {@ Override public booleanonPreDraw () {int height = view. getMeasuredHeight (); int width = view. getMeasuredWidth ();}});
Method 3 :
// Added the overall layout listener ViewTreeObserver vto = view. getViewTreeObserver (); vto. addOnGlobalLayoutListener (new OnGlobalLayoutListener () {@ Override public voidonGlobalLayout () {view. getViewTreeObserver (). removeGlobalOnLayoutListener (this); int height = view. getMeasuredHeight (); int width = view. getMeasuredWidth ();}});
Then, when the activity enters the runtime, the component size acquisition method is very simple. getWidth () and getHeight () are used directly ().