在一个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缺少。
谢谢!这显然是缺少的东西,我确实添加了它 - 但我仍然没有得到正确的答案。现在我得到了尺寸为63,0的尺寸,我应该可以得到更像480,780的尺寸。我不认为这是布局XML中的问题,因为Eclipse中的预览看起来很完美,我测试的布局非常基本。你能想到其他任何陷阱吗? – Jeremy 2011-03-23 17:28:14
编辑该问题以包含'measure()'和布局XML。作为上述数字的修正,一旦我将XML简化为现在的问题,数字就会回到0,0。 – Jeremy 2011-03-23 17:56:41
您没有正确调用measure(),阅读文档,您需要使用MeasureSpec.makeMeasureSpec()。你不能只传递一个宽度和一个高度。 – 2011-03-24 19:01:41