【问题标题】:Why does my FrameLayout have 0 height?为什么我的 FrameLayout 的高度为 0?
【发布时间】:2013-01-25 14:59:44
【问题描述】:

我有一个 FrameLayout,包含各种叠加的 ImageView:

<FrameLayout
    android:id="@+id/australia_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:id="@+id/australia"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/map_australia"
        />
    <ImageView
        android:id="@+id/nsw"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/map_nsw"
        android:visibility="invisible"
        />
    <ImageView
        android:id="@+id/victoria"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/map_victoria"
        android:visibility="invisible"
        />
        ...etc...
</FrameLayout>

在我的代码中,我尝试渲染我的 FrameLayout:

final Dialog dialog = new Dialog((Context) parent);
dialog.setContentView(R.layout.dialog_region);

FrameLayout fl = (FrameLayout) dialog.findViewById(R.id.australia_frame);
final int height = fl.getHeight();
Validate.isTrue(height > 0);

我的代码崩溃了:

java.lang.IllegalArgumentException: The validated expression is false
    at org.apache.commons.lang3.Validate.isTrue(Validate.java:180)

崩溃的行是Validate.isTrue(height &gt; 0);

为什么我的 FrameLayout 没有高度?有没有办法获得我的 FrameLayout 正在渲染的确切 px 高度和宽度?

【问题讨论】:

  • 你可以试试getMeasuredHeight() 吗?
  • 我认为您的对话框在您读取它的高度时尚未测量。

标签: android


【解决方案1】:

这可能对你有帮助

     FrameLayout target = (FrameLayout) dialog.findViewById(R.id.australia_frame);
    target.post(new Runnable() {

        @Override
        public void run() {             
            int width = target.getWidth();
                            int height = width/2;
            /*your code with width and height*/
        }

    });
}   

【讨论】:

  • 对于那些好奇为什么会这样的人,当onCreate 在你的 Activity 中执行时,UI 还没有被绘制到屏幕上,所以没有任何尺寸,因为它们还没有被布局屏幕。当setContentView 被调用时,会向UI 线程发送一条消息来为您的布局绘制UI,但将来会在onCreate 完成执行后发生。向 UI 线程发布 Runnable 会将 Runnable 放在 UI 线程的消息队列的末尾,因此将在屏幕绘制之后执行,因此所有内容都有尺寸。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-10
  • 1970-01-01
  • 2018-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多