2012-08-15 43 views
11

的高度我有一個的LinearLayout組高度match_parent如下:如何獲得的LinearLayout

<LinearLayout 
    android:id="@+id/list_layout" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" > 

我想這個的LinearLayout的高度。
我用下面的代碼:

LinearLayout ll_list = (LinearLayout)findViewById(R.id.list_layout); 
int h = ll_list.getHeight(); 

但它返回null。
我該怎麼辦?

+0

除非你將有一個後臺任務優化的位圖(或類似的東西)顯示在屏幕上之前,我真的不能在任何時候任何需要這個值的東西。如果您可以告訴我們關於您的應用程序的更多信息,我們可以爲您提供更好的設計方案。 – Budius 2012-08-15 08:26:31

+0

http://stackoverflow.com/a/41705445/5664529檢查一下,它可能會幫助你。 – 2017-01-17 20:00:05

回答

36

首先:你LinearLayout ID是left_layout,不list_layout

另外,ll_list.getHeight()將返回0(以及ll_list.getWidth()),如果它尚未繪製。

解決方案將得到高度的觀點是layouted後:

ll_list.post(new Runnable(){ 
    public void run(){ 
     int height = ll_list.getHeight(); 
    } 
}); 

,並確保您的ll_listfinal

+0

如何讓它被繪製。 – brian 2012-08-15 05:47:39

+0

@brian這不是你的問題。確保在繪製視圖後調用'getHeight()'。 – 2012-08-15 05:48:26

+0

@brian我提供了一個示例 – 2012-08-15 05:50:29

1
LinearLayout ll_list = (LinearLayout)findViewById(R.id.list_layout); 
                 ^^^^^^^^^^ 
+2

可能是他在問題中輸入錯誤。它甚至不會編譯,如果是這種情況 – 2012-08-15 05:44:07

+0

抱歉錯字錯誤。但不是它仍然是空的。 – brian 2012-08-15 05:44:26

+0

看到你的xml文件名並且改變id然後檢查它 – 2012-08-15 05:45:07

-6

試試這個代碼:

public static int getViewDimensions(View v,String what){ 
    int result = 0; 
    if (what.equalsIgnoreCase("height")) { 
     result = v.getHeight(); 
    } else { 
     result = v.getWidth(); 
    } 
    return result; 

} 

然後onBackPressed(),你可以得到你所需要的任何ViewLinear的widht和高度。

@Override 
public void onBackPressed() { 

    RelativeLayout banner = (RelativeLayout)findViewById(R.id.banner); 

    int h = getViewDimensions(banner, "height"); 
    int w = getViewDimensions(banner, "width"); 

    Log.v("Height*Widht", h +"*"+ w); 

} 
+1

任何你不建議只調用banner.getHeight()或banner.getWidth()的理由? – garlicman 2013-09-06 19:55:51

+0

因爲我想知道很多視圖的高度和寬度,所以我創建了上面的函數。 – 2015-05-11 17:43:39

+0

我也想根據視圖尺寸知道不同視圖之間的較大高度和寬度。 – 2015-05-11 17:45:09