Obtain the View component width and ViewTreeObserver,

Source: Internet
Author: User

Obtain the View component width and ViewTreeObserver,
View width and height measurement method:

There are three measurement methods:

1)(Directly in onCreate)

int w = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);  int h = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);  imageView.measure(w, h);  int height =imageView.getMeasuredHeight();  int width =imageView.getMeasuredWidth();  textView.append("\n"+height+","+width);

2)Both 2 and 3 get the width and height of the component after onCreate () is called.

ViewTreeObserver vto = imageView.getViewTreeObserver();  vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {      public boolean onPreDraw() {          int height = imageView.getMeasuredHeight();          int width = imageView.getMeasuredWidth();          textView.append("\n"+height+","+width);          return true;      }  });

3)

ViewTreeObserver vto2 = imageView.getViewTreeObserver();    vto2.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {      @Override        public void onGlobalLayout() {          imageView.getViewTreeObserver().removeGlobalOnLayoutListener(this);            textView.append("\n\n"+imageView.getHeight()+","+imageView.getWidth());      }    });

Note: method 1 performs onMeasure calculation once more than other methods, and the callback function of method 2 is called multiple times.

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.