2014-02-13 40 views
1

我需要在佈局中獲取某些視圖的座標。我已經嘗試做這樣(內onCreateView)片段中的視圖座標始終爲空

TextView[] tv = new TextView[3] 
tv[0] = (TextView) view.findViewById(R.id.content0); 
tv[1] = (TextView) view.findViewById(R.id.content1); 
tv[2] = (TextView) view.findViewById(R.id.content2); 
RectF[] positions = new RectF[3]; 

for (int i = 0; i < tv.length; i++) { 
    int top = tv[i].getTop(); 
    int left = tv[i].getLeft(); 
    int width = tv[i].getWidth(); 
    int height = tv[i].getHeight(); 
    positions[i] = new RectF(left, top, left + width, top + height); 

} 

但是,如果我嘗試打印位置數組logcat中,我獲得總0,0,0,0。怎麼了?

+1

您正在查找的信息在運行時可用,但僅在繪製視圖時纔可用。 – Blackbelt

回答

1

隨着黑帶的提及,您必須等待視圖的佈局才能獲得維度。 使用ViewTreeObserver。

getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
     @Override 
     public void onGlobalLayout() { 
      for (int i = 0; i < tv.length; i++) { 
       int top = tv[i].getTop(); 
       int left = tv[i].getLeft(); 
       int width = tv[i].getWidth(); 
       int height = tv[i].getHeight(); 
       positions[i] = new RectF(left, top, left + width, top + height); 

      } 
      getViewTreeObserver().removeOnGlobalLayoutListener(this); 

     } 
    });