我有一个自定义视图从RelativeLayout
大小应该是正方形的地方扩展,以及一个背景图像,match_parent
它的宽度和高度是它的孩子。还有一个按钮应该水平居中并与背景图像的底部对齐。
一切正常,直到我添加一些边距并将我的设备旋转到横向模式。在横向模式下,容器的宽度不知何故大于其高度,如下所示:
自定义视图只是一个从 RelativeLayout 扩展的简单类,我已经重写了它的onMeasure
方法,如下所示:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int size = Math.min(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.getSize(heightMeasureSpec));
int specSize = MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY);
super.onMeasure(specSize, specSize);
measureChild(bgImage, specSize, specSize); // bgImage is the flower image
setMeasuredDimension(size, size);
}
以及视图的布局:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" android:background="#eff1f1" android:padding="1dp">
<com.example.MyViewGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#e54eff"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" android:layout_margin="50dp">
<ImageView
android:id="@+id/myPic"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitCenter"
android:src="@drawable/flower"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:adjustViewBounds="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:id="@+id/button" android:layout_alignBottom="@+id/myPic" android:layout_centerHorizontal="true"/>
</com.example.MyViewGroup>
</RelativeLayout>
谁能指出我在这里做错了什么?如果这个问题之前已经回答过,有人可以给我一个链接吗?搜索后似乎找不到任何类似的问题。我正在为 API 11 开发并在运行 Android 4.04 的三星 Galaxy Tab 8.9 上进行测试。
谢谢!