2011-03-23 86 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你的情况)。