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 は消えました。

私は正しく実装していonMeasureないと思います。onLayout子ビューのサイズも変更する必要があると思います。しかし、私は今何をすべきかわかりません。


アップデート

TheDimasigのコメントに従って、コードをチェックして質問を更新しました。ありがとう

4

3 に答える 3

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メソッドでは、ImageViewを含むすべての子ビューでonMeasureを呼び出すのを忘れていると思います。あなたはあなたのすべての子供の見解を通り抜けて、次のようなものでそれらにonMeasureを呼び出す必要があります:

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