【问题标题】:layout() on manually-inflated View手动膨胀视图上的 layout()
【发布时间】: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() 调用。

【问题讨论】:

    标签: android layout view


    【解决方案1】:

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

    【讨论】:

    • 谢谢!这显然是缺少的东西,我确实添加了它——但我仍然没有得到正确的答案。现在我得到了 63,0 的尺寸,我应该得到更像 480,780 的尺寸。我认为布局 XML 中没有问题,因为 Eclipse 中的预览看起来很完美,而且我正在测试的布局非常基本。你能想到这里的任何其他问题吗?
    • 编辑问题以包括measure() 和布局 XML。作为对上面数字的更正,一旦我将 XML 简化为现在的问题,数字又回到了 0,0。
    • 您没有正确调用 measure(),请阅读文档,您需要使用 MeasureSpec.makeMeasureSpec()。你不能只传递一个宽度和一个高度。
    • 啊哈,错过了。当然现在可以了。非常感谢您的帮助!
    【解决方案2】:

    首先,inflate 不会考虑您在 xml 中指定的布局参数。你可以通过使用来解决这个问题

    inflater.inflate( R.layout.top_view_layout /* 资源id */, 父视图, false /* attachToRoot */);

    这将确保您将 match_parent 用于宽度和高度。

    如果您不想这样做,那么您应该首先为膨胀视图设置 LayoutParams。

    P.S.:AFAIK,布局方法将采用可显示的屏幕区域参数(左、上、右、下),但它会考虑显示视图的原始大小(在您的 0,0案例)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-18
      • 2016-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-12
      相关资源
      最近更新 更多