SoFunction
Updated on 2025-03-01

Implementation method for obtaining the height or width of the control in oncreate in Android

Implementation method for obtaining the height or width of the control in oncreate in Android

The onCreate function only provides an opportunity to initialize data, and the graph has not been officially drawn at this time. When the graphics have not been rendered, getWidth() or getHeight() gets the value 0. If you need an adaptive screen, you need to get the parent control size as soon as you enter the interface, and then you need to dynamically set the child control size in onCreate.

 Method 1:

Use the addOnPreDrawListener interface of the ViewTreeObserver class.

ViewTreeObserver vto = (); 
 
          (() { 
 
              @Override 
 
              publicboolean onPreDraw() { 
 
                   if(hasMeasured == false){ 
 
                        intwid = (); 
 
                        inthei = (); 
 
                        if(wid != 0 && hei != 0){ 
 
                            hasMeasured= true; 
 
                        } 
 
                   } 
 
                   returntrue; 
 
              } 
 
          }); 

Method 2:

Use the addOnGlobalLayoutListener interface of the ViewTreeObserver class.

If you have any questions, please leave a message or go to the community of this site to exchange and discuss. Thank you for reading. I hope it can help you. Thank you for your support for this site!