[Android 開發] 如何動態得到 View 的大小?

在 Android 的開發經驗上,我們很常使用內建的 Layout 來排版 ,而一個 Layout 其實就是一個 ViewGroup,有時我們會想要希望動態改變這個 View 的大小,但是如果一個 Layout 包成一個 Class 來呈現,要先算到這個 Layout 的大小其實並不容易。不過 Android 中提供一個很好的機制,在畫出 Layout 之前我們可以先得到 View 的大小。而以下為動態得到 View 大小的程式碼,就請大家參考囉!

 

import android.view.ViewTreeObserver.OnGlobalLayoutListener;
private void vSetMeasureWidthHeight()
{
  final View this_layout = this;
  this.getViewTreeObserver().addOnGlobalLayoutListener(
  new OnGlobalLayoutListener()
  {  
    boolean bIsFirstCall = true;
    @Override  
    public void onGlobalLayout() 
    {  
      if (bIsFirstCall) 
      {
        bIsFirstCall = false;
        m_iPixelWidth = this_layout.getMeasuredWidth();
        m_iPixelHeight = this_layout.getMeasuredHeight(); 
      }  
    }
  });  
}

 

在這個程式碼中,vSetMeasureWidthHeight 是包在一個繼承 LinearLayout 的 class 中,你可以在程式進入時就呼叫它,讓這個 View 被註冊一個監聽的事件。而 OnGlobalLayoutListener 預設會進入兩次,所以我們要用 bIsFirstCall 來控制,當然如果你不是程式設計師,這篇就自動無視吧!

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments