Android gets view width and height

Source: Internet
Author: User

Transferred from: http://blog.csdn.net/yangdeli888/article/details/25405263

In OnCreate () using View.getwidth () or view.getheiht () to get the width and height of the view, it seems that there is no problem, actually they go to the value is 0, not the result you want?

What is this for?

When the OnCreate () method is called, the interface is not visible and the memory loading component has not been drawn, and you are unable to get his size.

How can you get the size of the component before you draw it?

Here are three ways to verify:

Method One:
Measurement methods

?
12345 intwidth =View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);intheight =View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);view.measure(width,height);intheight=view.getMeasuredHeight(); intwidth=view.getMeasuredWidth();


Method Two:

?
123456789 //增加组件绘制之前的监听ViewTreeObserver vto =view.getViewTreeObserver(); vto.addOnPreDrawListener(newViewTreeObserver.OnPreDrawListener() {    @Override    publicbooleanonPreDraw() {        intheight =view.getMeasuredHeight();        intwidth =view.getMeasuredWidth();        }});

Method Three:

?
12345678910 //增加整体布局监听ViewTreeObserver vto = view.getViewTreeObserver();  vto.addOnGlobalLayoutListener(newOnGlobalLayoutListener(){     @Override    publicvoidonGlobalLayout() {       view.getViewTreeObserver().removeGlobalOnLayoutListener(this);             intheight =view.getMeasuredHeight();         intwidth =view.getMeasuredWidth();      } });

Then, when the activity enters the runtime, the component's size acquisition method is simple, directly getwidth () and GetHeight ().

Android gets view width and height

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.