Original link: http://www.cnblogs.com/wt616/archive/2012/05/11/2496180.html
In Android, it is sometimes necessary to measure the control, and the resulting control width and height can be used to do some calculations. This calculation is particularly important in situations where adaptive screens are required. Another convenience, because of the requirements of the reasons, I hope that once the interface, you can get the width and height of the control.
Unfortunately, according to my verification, the use of those methods reproduced on the Internet in the OnCreate function is still 0 (hope that the technology can be verified and reproduced), such as the measure method after the call Getmeasuredwidth value or 0.
The reason for this is that when the OnCreate function occurs, it simply provides the opportunity to initialize the data, and there is no formal drawing. The drawing is done in OnDraw, and the calculation is too late. The easy way to think about it is to expect to get its width and height immediately after the program has just measured a specified control, or initialize the data. This requires a way to listen to this event, fortunately, Android provides such a mechanism, using the Getviewtreeobserver method in the view class, you can get to the observer of the specified view, the moment before the control to draw a callback, so that the speed does not delay , the obtained data by is accurate, but this method may be repeatedly called after, so need to join the limit, the normal demand, only one time is enough, the code is as follows (this code is validated in the OnCreate callback function, in real time, because it is the listener, So the event has nothing to do with OnCreate):
Layout =(metrolayout) Findviewbyid (r.id.layout); Viewtreeobserver Vto=Layout.getviewtreeobserver (); Vto.addonpredrawlistener (NewViewtreeobserver.onpredrawlistener () { PublicBoolean Onpredraw () {if(hasmeasured = =false) { intHeight =metrolayout.getmeasuredheight (); intwidth =metrolayout.getmeasuredwidth ();//when you get to the width and height, you can use it to calculatehasmeasured=true; } return true; } });
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Android Gets the width and height of the control in OnCreate