2013-11-04 28 views
0

例如,這是mButton安卓:如何獲得一個視圖的高度

<Button 
    android:id="@+id/mbtn" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:text="mButton" /> 

這是我試圖讓高度:

int height = mButton.getLayoutParams.height; 

但是,當我登錄它,它說高度是-2。我認爲這可能是「wrap_content」的整數值。那麼我怎麼才能得到實際的身高?謝謝!

回答

3

如果你想在activty視圖 你可以在這個方法得到的寬度或高度..

yourview.getHeight(); 

返回零(0)窗口只有它具有width..in以下方法就可以高度和一個視圖的寬度..

@Override 
public void onWindowFocusChanged(boolean hasFocus) { 
    super.onWindowFocusChanged(hasFocus); 
    yourview.getHeight(); 
    yourview.getWidth(); 
} 
0

佈局後發生呼叫View.getHeight()

public final int getHeight()

返回你的視線的高度。

返回
視圖的高度,以像素爲單位。

正如你所猜測的,layoutParams.height只是在你的情況下,wrap_content的值,即-2。您可以將layoutParams.height設置爲所需的高度,但即使如此,在完成所有佈局後,視圖實際上並不會達到最終的高度。因爲它增加了後按鈕的初始化後

1

覆蓋的方法onWindowFocusChanged(布爾hasFocus);

內編寫代碼,

@Override 
public void onWindowFocusChanged(boolean hasFocus) { 
super.onWindowFocusChanged(hasFocus); 
mbtn.getHeight(); 
mbtn.getWidth(); 
} 

它會給視圖尺寸正確的結果。

相關問題