8

这是我的代码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 消失了。

我认为我没有实施onMeasureonLayout正确。我想我也需要调整子视图的大小。但我不知道现在该怎么办。


更新

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

4

3 回答 3

19

最简单的方法是在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);
}

通过这种方式,您可以获得所需的尺寸,但不必手动测量孩子。

于 2014-04-22T22:20:24.070 回答
10

您看不到任何子视图,因为您没有onMeasure正确覆盖该方法。您可以让超类实现逻辑(因此将显示子视图),然后重置计算的宽度和高度MyFrameLayout

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    // let the super class handle calculations
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    // set again the dimensions, this time calculated as we want
    setMeasuredDimension(getMeasuredWidth(), getMeasuredHeight() / 2);
    // this is required because the children keep the super class calculated dimensions (which will not work with the new MyFrameLayout sizes) 
    final int count = getChildCount();
    for (int i = 0; i < count; i++) {
        final View v = getChildAt(i);
        // this works because you set the dimensions of the ImageView to FILL_PARENT          
        v.measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth(),
                MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(
                getMeasuredHeight(), MeasureSpec.EXACTLY));
    }
}

如果您发布的布局不是您的完整布局,那么我的代码可能不起作用。

于 2012-09-11T10:21:14.910 回答
2

我想在您的onMeasure方法中,您忘记在所有子视图上调用 onMeasure,包括您的 ImageView。您必须遍历所有子视图并在它们上调用 onMeasure,如下所示:

    for (int i = 0; i < getChildCount(); i++) {
        getChildAt(i).measure(....);
    }
于 2012-09-11T08:47:11.370 回答