This article describes the method of Android programming to obtain component size. Share it for your reference, as follows:
Using() or () in oncreate() to get the width and height of the view seems to be fine, but in fact, their value is 0, which is not the result you want?
Why is this?
When calling the oncreate() method, the interface is invisible and the memory loading component has not been drawn yet, so you cannot get its size.
How about thatBefore drawing componentsCan you get the size of this component?
Here are three methods, verified:
Method 1:
//Measurement methodint width =(0,); int height =(0,); (width,height); int height=(); int width=();
Method 2:
//Add to listen before component drawingViewTreeObserver vto =(); (new () { @Override public ooleanonPreDraw() { int height =(); int width =(); } });
Method 3:
//Add overall layout monitoringViewTreeObserver vto = (); (new OnGlobalLayoutListener(){ @Override public voidonGlobalLayout() { ().removeGlobalOnLayoutListener(this); int height =(); int width =(); } });
So,When the activity enters the runtime, the component's size acquisition method is very simple, directly getWidth() and getHeight().
For more information about Android related content, please check out the topic of this site:Android development introduction and advanced tutorial》、《Android debugging skills and solutions to common problems》、《Summary of the usage of basic Android components》、《Android View View Tips Summary》、《Android layout layout tips summary"and"Android control usage summary》
I hope this article will be helpful to everyone's Android programming design.