FBI Warning: Welcome reprint, but please indicate source: http://blog.csdn.net/codezjx/article/details/45341309 , do not use for commercial purposes without my consent, thank you for your support!
when we are in onCreate () callback method to invoke the View of the getwidth (), getheight () , GetTop () , GetLeft () and Other methods , it is not possible to get the correct value at this time, it will only return 0 .
Why is it?
because view The display must go through the measure (measurement), layout (layout) and draw (drawing) process. And in measure layout After the process is complete, view width, height , top , left oncreate execution.
workaround One: rewrite the Activity 's onwindowfocuschanged method
@Overridepublic void Onwindowfocuschanged (Boolean hasfocus) {super.onwindowfocuschanged (hasfocus);//Here it is normal to get width, Height, etc.}
(Note: When the Activity Gets or loses focus, it is called.) This method is recalled when the Activity is initialized and ready to be displayed. So, as long as you want to do something that is triggered immediately after the Activity is loaded, you can do it here. )
workaround Two: Register listener for View Ongloballayoutlistener
Mview.getviewtreeobserver (). Addongloballayoutlistener (New Ongloballayoutlistener () {@Overridepublic void Ongloballayout () {///Here the width, height, etc. mview.getviewtreeobserver () can be obtained normally. Removeongloballayoutlistener (this);});
(Description: A callback function that executes when the visibility of the view tree or the global layout state changes, and the layout process is completed and may be called multiple times, so you can remove the listener when you are finished)
The problem of the width,height of view in OnCreate is 0