在onCreate方法中擷取某個View的寬度和高度

來源:互聯網
上載者:User
在onCreate方法中擷取某個View的寬度和高度
    部落格分類:

  • Android

有時候需要在onCreate方法中知道某個View組件的寬度和高度等資訊,而直接調用View組件的getWidth()、getHeight()、getMeasuredWidth()、getMeasuredHeight()、getTop()、getLeft()等方法是無法擷取到真實值的,只會得到0。這是因為View組件布局要在onResume回調後完成。下面提供實現方法,onGlobalLayout回調會在布局完成時自動調用

 

Java代碼  
  1. final LinearLayout imageViewContainer = (LinearLayout)findViewById(R.id.crop_photo_image_view_container);  
  2.         imageViewContainer.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {  
  3.             boolean isFirst = true;//預設調用兩次,這裡只讓它執行一次回調  
  4.             @Override  
  5.             public void onGlobalLayout() {  
  6.                 if (isFirst) {  
  7.                     isFirst = false;  
  8.                     //現在布局全部完成,可以擷取到任何View組件的寬度、高度、左邊、右邊等資訊  
  9.                     Log.i("CDH", "Global W:"+imageViewContainer.getMeasuredWidth()+"  H:"+imageViewContainer.getMeasuredHeight());  
  10.                 }  
  11.             }  
  12.         });  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.