(Android) Some solutions for view.getheight or getwidth 0 o'clock

Source: Internet
Author: User

In the Android development process, often need to dynamically change the size of the view, some of the size of the view may need to be set according to other view size, or you need to get some view size to do something, but it is possible that you need to get this value in OnCreate, But some Android-based developers are aware that Android does not know the size of these view in the OnCreate method (or Onresume). What do we need to do at this time?

1. The first form of violence

You can write a sub-thread, let it delay hundreds of mm first, and then go to get the size of the view, haha, this method is very ridiculous, I think so.

2. Get in onwindowfocuschanged monitoring

The time to call the Onwindowfocuschanged method is when the window gets to the focus, and the view is already drawn, and the correct height and width are available.

3. Using View.post

1MView =Findviewbyid (r.id.textview);2Mview.post (NewRunnable () {3 @Override4              Public voidrun () {5                 intViewwidth =mview.getwidth ();6                 intViewheight =mview.getheight ();7LOG.D (TAG, "viewwidth:" + viewwidth + "\nviewheight:" +viewheight);8             }9});

This way can let the runable in the Run method after the completion of the execution, but this way I do not know why, sometimes I need to click on the screen, or do other operations, will be executed, unknown so

4. Using handler

This way most people can think

5. Monitoring Draw/layout Event: Viewtreeobserver

Viewtreeobserver Greenobserver =Mview.getviewtreeobserver (); Greenobserver.addonpredrawlistener (NewOnpredrawlistener () {@Override Public BooleanOnpredraw () {mview.getviewtreeobserver (). Removeonpredrawlistener ( This); intHeight =Mview.getheightreturn true; }                        }); 

(Android) Some solutions for view.getheight or getwidth 0 o'clock

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.