The problem of the width,height of view in OnCreate is 0

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.