Android obtains the width and height of the control in OnCreate.

Source: Internet
Author: User

Android obtains the width and height of the control in OnCreate.

A demo. in xml layout, the height of a row is half that of other rows. Previously, layout_weight was used to produce unsatisfactory results.

 

   
            
          
       
   
  
 

 

 

Although it works, if there is too much content in it, this layout will not work. Therefore, we dynamically set the height of the mobile phone screen based on its size.

 

 
Public class HomeActivity extends Activity {private LinearLayout homelayout; // parent private LinearLayout home1; private LinearLayout home2; private LinearLayout home3; private LinearLayout home4; boolean hasMeasured = false; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_home); home1 = (LinearLayout) findViewById (R. id. home_content_section1); home2 = (LinearLayout) findViewById (R. id. home_content_section2); home3 = (LinearLayout) findViewById (R. id. home_content_section3); home4 = (LinearLayout) findViewById (R. id. home_content_section4); homelayout = (LinearLayout) findViewById (R. id. home_content); ViewTreeObserver vto = homelayout. getViewTreeObserver (); vto. addOnPreDrawListener (new ViewTreeObserver. onPreDrawListener () {@ Override public boolean onPreDraw () {if (hasMeasured = false) {// get the width and height of homelayout int height = homelayout. getMeasuredHeight (); // int width = homelayout. getMeasuredWidth (); android. view. viewGroup. layoutParams lp1 = home1.getLayoutParams (); lp1.height = height * 2/7; android. view. viewGroup. layoutParams lp2 = home2.getLayoutParams (); lp2.height = height * 2/7; android. view. viewGroup. layoutParams lp3 = home3.getLayoutParams (); lp3.height = height * 1/7; android. view. viewGroup. layoutParams lp4 = home4.getLayoutParams (); lp4.height = height * 2/7; hasMeasured = true;} return true ;}});}
 

Related Article

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.