Android tutorial _ Get the width and height of the Android control.

Source: Internet
Author: User

Android tutorial _ Get the width and height of the Android control.

Reprinted: http://blog.csdn.net/johnny901114/article/details/7839512

We all know that the height of the control obtained in onCreate () is 0. Why? Let's take a look at the example:

First, we can write a control, which is very simple:

Public class MyImageView extends ImageView {public MyImageView (Context context, AttributeSet attrs) {super (context, attrs);} public MyImageView (Context context) {super (context );} @ Override protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {super. onMeasure (widthMeasureSpec, heightMeasureSpec); System. out. println ("onMeasure I was called" + System. currentTimeMillis ();} @ Override protected void onDraw (Canvas canvas) {super. onDraw (canvas); System. out. println ("onDraw I was called" + System. currentTimeMillis ());}}

Layout file:

<com.test.MyImageView        android:id="@+id/imageview"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:src="@drawable/test" />

OnCreate () of the tested Activity ():

@ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); System. out. println ("execution completed .. "+ System. currentTimeMillis ());}

Now let's look at the results:

  

Description: After the onCreate method is executed, the control we define will be measured. Therefore, we use the view in the onCreate method. the height or width of the getHeight () control must be 0, because it has not been measured, that is, it does not know how high it is, and you can get its size at this time, certainly not.

We can't help but solve this problem. We found the following solution on the Internet:

// ------------------------------------------------ Method 1 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); // ------------------------------------------------- method 2 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 ;}}); // ------------------------------------------------- method 3 ViewTreeObserver vto2 = imageView. getViewTreeObserver (); vto2.addOnGlobalLayoutListener (new OnGlobalLayoutListener () {@ Override public void onGlobalLayout () {imageView. getViewTreeObserver (). removeGlobalOnLayoutListener (this); textView. append ("\ n" + imageView. getHeight () + "," + imageView. getWidth ());}});

Where are these three methods? I forgot to find them now.

Which method should we use when necessary?

Change the test Activity to the following:

@ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); final ImageView imageView = (ImageView) findViewById (R. id. imageview); // -------------------------------------------------- method 1 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); System. out. println ("execution completed .. "+ System. currentTimeMillis ());}

  

Next, let's take a look at the following output methods:

Change the test Activity to the following:

@ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); final ImageView imageView = (ImageView) findViewById (R. id. imageview); // ------------------------------------------------- method 2 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 ;}});}

The result is as follows:

  

Method 3 is no longer tested. method 2 !!!

So what is the difference between method 3 and method 3 in execution?

We add a TextView to the layout file to record the width and height of the control.

<ScrollView        android:layout_width="wrap_content"        android:layout_height="wrap_content" >        <TextView            android:id="@+id/text"            android:layout_width="wrap_content"            android:layout_height="wrap_content" />    </ScrollView>

Let's test the method first:

@ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); final ImageView imageView = (ImageView) findViewById (R. id. imageview); // ------------------------------------------------- method 2 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 ;}});}

The result is as follows:

  

Let's test method 3 again.

@ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); final ImageView imageView = (ImageView) findViewById (R. id. imageview); // ------------------------------------------------- method 3 ViewTreeObserver vto2 = imageView. getViewTreeObserver (); vto2.addOnGlobalLayoutListener (new OnGlobalLayoutListener () {@ Override public void onGlobalLayout () {imageView. getViewTreeObserver (). removeGlobalOnLayoutListener (this); textView. append ("\ n" + imageView. getHeight () + "," + imageView. getWidth ());}});}

The output result is as follows:

  

I don't need to mention the difference between method 2 and method 3.

Conclusion: Which method should be used to obtain the width and height of the control?

Method 1: An onMeasure () method is called once more than the other two methods. Although this method looks simple, however, if you want to calculate the target control for a large time (such as listView), we do not recommend that you use it.

Method 2: its callback method will be called many times, and it will still be called when sliding TextView, so it is not recommended.

Method 3: suitable.

Of course, the actual application depends on the actual situation.

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.