In Android, you sometimes need to measure the widget. The width and height of the widget can be calculated. This kind of computing is especially important when adaptive screens are needed. In addition, we hope that the width and height of the control can be obtained as soon as you enter the interface.
Unfortunately, according to my verification, the methods reposted on the Internet still get 0 in the OnCreate function (I hope the technical personnel can verify it and then repost it ), for example, the value of getMeasuredWidth called after the Measure method is still 0.
The reason is that when the OnCreate function occurs, it only provides the opportunity for data initialization. At this time, the image has not been formally drawn. While the drawing is carried out in OnDraw, the calculation is too late. One easy way to think of is to calculate the width and height of a specified control immediately or initialize the data after the program has just measured it. This requires a method to monitor the occurrence of this event. Fortunately, Android provides such a mechanism to use the getViewTreeObserver method in the View class to obtain the observer of the specified View, the callback is performed immediately before the control is drawn, so that the speed is not delayed and the data obtained is accurate. However, this method may be called repeatedly later, so you need to add restrictions, under normal requirements, only one calculation is enough. The Code is as follows (this code passes verification in the OnCreate callback function, in real time, because it is a listener, so the event has nothing to do with OnCreate ):
Copy codeThe Code is as follows: layout = (MetroLayout) findViewById (R. id. layout );
ViewTreeObserver vto = layout. getViewTreeObserver ();
Vto. addOnPreDrawListener (new ViewTreeObserver. OnPreDrawListener ()
{
Public boolean onPreDraw ()
{
If (hasMeasured = false)
{
Int height = metroLayout. getMeasuredHeight ();
Int width = metroLayout. getMeasuredWidth ();
// Obtain the width and height for calculation.
HasMeasured = true;
}
Return true;
}
});