手动膨胀视图上的layout()

Jer*_*emy 4 layout android view

在 中Activity,我手动View从 XML 扩充对象,如下所示:

    LayoutInflater inflater = LayoutInflater.from (this);
    View topView = inflater.inflate (R.layout.topview_layout, null);
Run Code Online (Sandbox Code Playgroud)

我不会将视图添加到任何显示层次结构中,而是使用它来生成然后显示的位图。由于这些位图将是我的(主)屏幕的大小,因此我尝试导致布局发生:

    Display display = ((WindowManager) getSystemService (Context.WINDOW_SERVICE))
                        .getDefaultDisplay();
    topView.measure (display.getWidth (), display.getHeight ());
    topView.layout (0, 0, display.getWidth (), display.getHeight ());
Run Code Online (Sandbox Code Playgroud)

(它在上面的代码中获得了正确的显示尺寸。)

topView是一个LinearLayout包含一些其他视图的。其中之一是ImageView

    ImageView childView = (ImageView) pageView.findViewById (R.id.textArea);
Run Code Online (Sandbox Code Playgroud)

然而,在调用以下命令后,该视图似乎从未被告知其尺寸layout()

    int childViewWidth = childView.getWidth ();
    int childViewHeight = childView.getHeight ();
Run Code Online (Sandbox Code Playgroud)

(上述代码检索到的维度是 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>
Run Code Online (Sandbox Code Playgroud)

我将非常感谢任何线索!

注意:编辑以添加布局 XML 和Romain Guymeasure()指出缺少的调用。

Rom*_*Guy 5

在调用layout()之前需要先调用measure()。