【发布时间】:2011-03-23 17:15:46
【问题描述】:
在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 和 Romain Guy 指出缺少的 measure() 调用。
【问题讨论】: