2013-01-25 63 views
0

我有一個FrameLayout裏,含有各種疊加ImageViews:爲什麼我的FrameLayout有0高度?

<FrameLayout 
    android:id="@+id/australia_frame" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 
    <ImageView 
     android:id="@+id/australia" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:src="@drawable/map_australia" 
     /> 
    <ImageView 
     android:id="@+id/nsw" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:src="@drawable/map_nsw" 
     android:visibility="invisible" 
     /> 
    <ImageView 
     android:id="@+id/victoria" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:src="@drawable/map_victoria" 
     android:visibility="invisible" 
     /> 
     ...etc... 
</FrameLayout> 

在我的代碼我試圖使我的FrameLayout:

final Dialog dialog = new Dialog((Context) parent); 
dialog.setContentView(R.layout.dialog_region); 

FrameLayout fl = (FrameLayout) dialog.findViewById(R.id.australia_frame); 
final int height = fl.getHeight(); 
Validate.isTrue(height > 0); 

我的代碼崩潰與:

java.lang.IllegalArgumentException: The validated expression is false 
    at org.apache.commons.lang3.Validate.isTrue(Validate.java:180) 

線這是崩潰是Validate.isTrue(height > 0);

爲什麼我的FrameLayout沒有高度?有沒有辦法讓我的FrameLayout渲染的確切像素高度和寬度?

+0

你可以試試'getMeasuredHeight()'? – 2013-01-25 06:54:27

+0

我認爲你的對話框在你讀取它的高度時沒有測量過。 – Leonidos

回答

4

這可能會幫助你

 FrameLayout target = (FrameLayout) dialog.findViewById(R.id.australia_frame); 
    target.post(new Runnable() { 

     @Override 
     public void run() {    
      int width = target.getWidth(); 
          int height = width/2; 
      /*your code with width and height*/ 
     } 

    }); 
} 
+6

對於那些好奇的原因,當你的Activity中執行'onCreate'時,UI還沒有被繪製到屏幕上,所以沒有任何尺寸,因爲它們還沒有被放置在屏幕上。當調用'setContentView'時,會向UI線程發佈一條消息來爲您的佈局繪製UI,但在'onCreate'完成執行後將來會發生。向UI線程發佈'Runnable'會將'Runnable'放置在UI線程的消息隊列的末尾,因此將在繪製屏幕後執行,因此所有內容都有尺寸。 –

+1

@JasonRobinson很好的解釋..... – Pragnani

相關問題