How to get to the height of the Android control

Source: Internet
Author: User

Many people in the activity main thread call GetWidth, getmeasuredwidth, but get not the width of the view, this is because the view is not finished drawing, of course, what to do?

Method One, measure yourself:

int w = View.MeasureSpec.makeMeasureSpec (0,view.measurespec.unspecified); int h = View.MeasureSpec.makeMeasureSpec (0, View.MeasureSpec.UNSPECIFIED); View.measure (W, h); int height = view.getmeasuredheight (); int width = Vew.getmeasuredwidth ();

Method Two, add the drawing listener and get the size of the view after the drawing finishes:

View.getviewtreeobserver (). Addonpredrawlistener (New viewtreeobserver.onpredrawlistener ()  {              public boolean onpredraw ()  {                  View.getviewtreeobserver (). Removeonpredrawlistener (This);                 int height = view.getmeasuredheight ();                  int width  = view.getmeasuredwidth ();                  return true;              }         });

    方法三,添加全局布局变化监听:

View.getviewtreeobserver (). Addongloballayoutlistener (New Ongloballayoutlistener () {@Override Pub                 LIC void Ongloballayout () {view.getviewtreeobserver (). Removeglobalonlayoutlistener (this);                View.getheight ();            View.getwidth (); }           });

How to get to the height of the Android control

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.