Android 工作室拒绝将视图放入自定义容器中

Android studio refuses to put views inside custom container

我知道某处有愚蠢的错误,但我不知道在哪里。 我得到了以下容器的代码:

public class ImagesView extends LinearLayout {
public ImagesView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public ImagesView(Context context) {
    super(context);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int widthSize = MeasureSpec.getSize(widthMeasureSpec);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);
    float ar=(float)896/768;
    this.setMeasuredDimension(widthSize, (int) (widthSize/5*(1f/ar)));
    //this.setMeasuredDimension(1280,240);
}
}

布局xml:

<?xml version="1.0" encoding="utf-8"?>
<com.rhyboo.net.test.ImagesView  xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/holo_red_light">

<Button
    android:text="Button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/button3"
    android:layout_weight="1" />
</com.rhyboo.net.test.ImagesView>

在 android studio 中,我可以看到我的容器大小设置正确,但如果我向容器中添加一些东西,它会将子视图显示为零大小:

我做错了什么?

您的 onMeasure 不会调用 super.onMeasure... 因此永远不会测量孩子。此外,在调用 parents onMeasure 时,您可能希望将模式设置为 EXACTLY for width and/or height.