2011-03-23 65 views
3

在一個Activity,我手動從XML充氣一個View對象如下:佈局()上手動充氣視圖

LayoutInflater inflater = LayoutInflater.from (this); 
    View topView = inflater.inflate (R.layout.topview_layout, null); 

我不會被添加到視圖的任何顯示的層次結構,而是使用它會生成我將顯示的位圖。由於這些位圖將是我(主)屏幕的大小,我儘量使佈局發生:

Display display = ((WindowManager) getSystemService (Context.WINDOW_SERVICE)) 
         .getDefaultDisplay(); 
    topView.measure (display.getWidth(), display.getHeight()); 
    topView.layout (0, 0, display.getWidth(), display.getHeight()); 

(它越來越顯示的適當大小在上面的代碼。)

topView是一個LinearLayout其中包含一些其他意見。其中之一是一個ImageView

ImageView childView = (ImageView) pageView.findViewById (R.id.textArea); 

然而,這種觀點似乎從未被調用layout()後約其尺寸通知:

int childViewWidth = childView.getWidth(); 
    int childViewHeight = childView.getHeight(); 

(由上面的代碼中檢索到的尺寸是0, 0.)

以上所有代碼都是線性發生的,並且是從我的Activity子類'onCreate()方法中調用的。

佈局XML我與測試:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     android:id="@+id/topView" 
     android:orientation="vertical" 
     android:background="@color/blue" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent"> 
    <ImageView 
     android:id="@+id/textArea" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:background="@color/gold"/> 
</LinearLayout> 

我最欣賞任何線索!

注意:編輯添加布局XML和measure()調用指出由Romain Guy缺少。

回答

4

您需要在調用layout()之前調用measure()。

+0

謝謝!這顯然是缺少的東西,我確實添加了它 - 但我仍然沒有得到正確的答案。現在我得到了尺寸爲63,0的尺寸,我應該可以得到更像480,780的尺寸。我不認爲這是佈局XML中的問題,因爲Eclipse中的預覽看起來很完美,我測試的佈局非常基本。你能想到其他任何陷阱嗎? – Jeremy 2011-03-23 17:28:14

+0

編輯該問題以包含'measure()'和佈局XML。作爲上述數字的修正,一旦我將XML簡化爲現在的問題,數字就會回到0,0。 – Jeremy 2011-03-23 17:56:41

+1

您沒有正確調用measure(),閱讀文檔,您需要使用MeasureSpec.makeMeasureSpec()。你不能只傳遞一個寬度和一個高度。 – 2011-03-24 19:01:41

1

首先是膨脹不會考慮您在xml中指定的佈局參數。您可以通過使用

 
inflater.inflate(R.layout.top_view_layout /* resource id */, 
        parentView, 
        false /* attachToRoot */);

這將確保您在寬度和高度都使用match_parent。

OR

如果你不想這樣做,那麼你應該先設置的LayoutParams的膨脹視圖。 PS:AFAIK,佈局方法將採用屏幕區域可用於顯示的參數(左,上,右,下),但它會考慮視圖的原始大小以顯示(這是0,0 in你的情況)。