Obtain the width and height of a view in the oncreate method.
Sometimes you need to know the width and height of a view component in the oncreate method, and directly call the getwidth (), getheight (), getmeasuredwidth (), getmeasuredheight () gettop (), getleft (), and other methods cannot obtain the actual value, and only 0 is obtained. This is because the view component layout must be completed after the onresume callback. The implementation method is provided below. The ongloballayout callback will be automatically called when the layout is complete.
Java code
- Final linearlayout imageviewcontainer = (linearlayout) findviewbyid (R. Id. crop_photo_image_view_container );
- Imageviewcontainer. getviewtreeobserver (). addongloballayoutlistener (New ongloballayoutlistener (){
- Boolean isfirst = true; // It is called twice by default. Only One callback is executed here.
- @ Override
- Public void ongloballayout (){
- If (isfirst ){
- Isfirst = false;
- // Now the layout is complete. You can obtain the width, height, left, right, and other information of any view component.
- Log. I ("CDH", "Global W:" + imageviewcontainer. getmeasuredwidth () + "H:" + imageviewcontainer. getmeasuredheight ());
- }
- }
- });