How to get the width and height of a view in the OnCreate method

Source: Internet
Author: User

You can get the width and height of the view through the view's GetWidth () and GetHeight ().

However, what might disappoint you is that if you call these two functions directly within the OnCreate method, you will get to 0.

Why is it?

This is because, when OnCreate is called, the contents of the view are being layoutinflater to populate the XML layout.

This process fills the layout, but temporarily does not set the size of the view.

So when does the view actually get its size size?

It is actually after layout, and layout is after the OnCreate call.

So, what should we do if we want to get the size of the view in the OnCreate method?

In fact, the solution is still some, is the use of the view of the Post method .

Don't say much nonsense, look at the code:

protected void onCreate (Bundle savedinstancestate) {    super. OnCreate (savedinstancestate);    Setcontentview (R.layout.main);     = Findviewbyid (r.id.main_my_view);    View.post (new  Runnable () {            //  Get size of view after layout         @Override          Public void run () {            "view has width:" +view.getwidth () + "and Height:" +view.getheight ());        }    );} 

How to get the width and height of the view in the OnCreate method

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.