android – 扩展FrameLayout,子视图将不再显示

这是我的FrameLayout代码
<FrameLayout
        android:layout_width="fill_parent" android:layout_height="wrap_content">
    <ImageView
            android:id="@+id/frameView"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:src="@drawable/image1"
            />
</FrameLayout>

ImageView很好.

现在我有一个从FrameLayout扩展的自定义布局,例如MyFrameLayout.

在MyFrameLayout中,我希望布局的高度始终是宽度的一半,所以我的代码是:

public class MyFrameLayout extends FrameLayout {

     // 3 constructors just call super

     @Override
     protected void onMeasure(int widthMeasureSpec,int heightMeasureSpec) {
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = (int) (width * 0.5);
        setMeasuredDimension(width,height);
    }
}

然后在xml中使用它:

<com.test.MyFrameLayout
        android:layout_width="fill_parent" android:layout_height="wrap_content">
    <ImageView
            android:id="@+id/frameView"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:src="@drawable/image1"
            />
</com.test.MyFrameLayout>

但现在内部的ImageView消失了.

我想我没有正确实现onMeasure或onLayout.我想我也需要调整孩子们的观点.但我现在不知道该怎么做.

UPDATE

根据TheDimasig的评论,我刚检查了我的代码并更新了我的问题.谢谢

解决方法

最简单的方法是更改​​onMeasure中的measurespec,但仍然调用super:
@Override
 protected void onMeasure(int widthMeasureSpec,int heightMeasureSpec) {
    int width = MeasureSpec.getSize(widthMeasureSpec);
    int height = (int) (width * 0.5);
    heightMeasureSpec = MeasureSpec.makeMeasureSpec(height,MeasureSpec.EXACTLY);
    super.onMeasure(widthMeasureSpec,heightMeasureSpec);
}

这样您就可以获得所需的尺寸,但不必手动测量子尺寸.

相关文章

Android 通过adb shell命令查看内存,CPU,启动时间,电量等...
Monkey Android app稳定性测试工具之Monkey使用教程 by:授客...
Android 常见adb命令 by:授客 QQ:1033553122 1、 查看所有已...
这篇“android轻量级无侵入式管理数据库自动升级组件怎么实现...
今天小编给大家分享一下Android实现自定义圆形进度条的常用方...
这篇文章主要讲解了“Android如何解决字符对齐问题”,文中的...