2011-11-20 78 views

回答

37
Display display = getWindowManager().getDefaultDisplay(); 
View view = findViewById(R.id.YOUR_VIEW_ID); 
view.measure(display.getWidth(), display.getHeight()); 

view.getMeasuredWidth(); // view width 
view.getMeasuredHeight(); //view height 
+0

請標記爲已解決^^ –

+4

您可能還要記住,如果視圖沒有被充氣,它的寬度和高度將會是0. – Joru

+0

您是對的Joru。我使用ViewTreeObserver並解決了我的問題。感謝所有試圖回答的人。 –

23

@dmytrodanylyk - 我認爲它會返回寬度&高度爲0,所以你需要使用下面的事情

LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
View contentview = inflater.inflate(R.layout.YOURLAYOUTNAME, null, false); 
contentview.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED); 
int width = contentview.getMeasuredWidth(); 
int height = contentview.getMeasuredHeight(); 

它會給你正確的高度&寬度。

+0

這就是我需要確定是否應該開始一個新的複選框,首先使它成爲一個單一的行,然後通過計算寬度來防止溢出...完美謝謝。來自 - > http://stackoverflow.com/a/24054428/1815624 – CrandellWS

9

您應該使用OnGlobalLayoutListener,它被視爲在視圖上進行了更改,但在繪製之前進行了更改。

costumView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 

    @Override 
    public void onGlobalLayout() { 

     costumView.getWidth(); 

    } 
}); 
2

我喜歡使用這種技術,因爲每my answer on a related question

郵政從onCreate()可運行視圖已經被創建時將被執行:

contentView = findViewById(android.R.id.content); 
    contentView.post(new Runnable() 
    { 
     public void run() 
     { 
      contentHeight = contentView.getHeight(); 
     } 
    }); 

該代碼將在運行主要UI線程,在onCreate()完成後。

0

這是最好的方法......工作!

public void onWindowFocusChanged(boolean hasFocus) {   
    super.onWindowFocusChanged(hasFocus); 

    if (fondo_iconos_height==0) { // to ensure that this does not happen more than once 
     fondo_iconos.getLocationOnScreen(loc); 
     fondo_iconos_height = fondo_iconos.getHeight(); 
     redraw_function(); 
    } 

} 
5
Display display = getWindowManager().getDefaultDisplay(); 
Point size = new Point(); 
display.getSize(size); 
view.measure(size.x, size.y); 
int width = view.getMeasuredWidth(); 
int height = view.getMeasuredHeight(); 
0
yourView.measure(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); 
    int yourView= m_hidableRowContainer.getMeasuredHeight(); 

就是這樣。

+0

'measure'需要一對'View.MeasureSpec'整型常量,而不是佈局參數常量。 – Tom

相關問題