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 the verification, the use of those methods reproduced on the net 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):
Final view view = findviewbyid (r.id.layout); Viewtreeobserver vto = view.getviewtreeobserver (); Vto.addonpredrawlistener (new Viewtreeobserver.onpredrawlistener () { public boolean onpredraw () { if (Hasmeasured == false) { int height = view.getmeasuredheight (); int width = view.getmeasuredwidth (); // After obtaining the width and height, you can use it to calculate the hasMeasured = true; } return true; //returns True to the available status } });
This article is from the "Maybe You" blog, please be sure to keep this source http://wjyzxc.blog.51cto.com/5725897/1636622
Android Gets the width and height of the control in OnCreate