Android gets the implementation code for the width and height of the control in OnCreate

  • 2020-05-05 13:16:15
  • OfStack

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 when an adaptive screen is required. Another convenience, because of the requirements, want to enter the interface, you can get the width and height of the control.

Unfortunately, according to my verification, those methods that are reposted online still get 0 in the OnCreate function (I hope the technical people can verify themselves and repost), for example, Measure method after the call getMeasuredWidth value is still 0.

The reason is that when the OnCreate function occurs, it only provides an opportunity to initialize the data, and the graph has not yet been formally drawn. Drawing the graph in OnDraw is too late to calculate. The easy way to think about it is to want to calculate or initialize the width and height of a given control as soon as the program has measured it. It needs a way to listen to this event, fortunately Android provides such a mechanism, utilization of getViewTreeObserver View class, can get to the specified View observer, in painting the moment before the control callback, don't delay again on this speed, the data is accurate, but in this method may be called repeatedly, so need to add restrictions, general requirements, calculated only once is enough, the code is as follows (this code in the OnCreate callback function verification through, real time, because it is a listener, So the event has nothing to do with OnCreate) :

 
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(); 
// After the width and height are obtained, they can be used for calculation  

hasMeasured = true; 

} 
return true; 
} 
}); 

Related articles: