I have a custom view extended from RelativeLayout
where the size should be square, and a background image with match_parent
for it's width and height as it's child. There is also a button that should be centered horizontally and aligned with the background image's bottom.
All works well, until I add in some margin and rotate my device into landscape mode. In landscape mode, the container's width somehow gets larger than its height, as shown below:
The custom view is just a simple class extended from RelativeLayout, and I've overridden its onMeasure
method as follows:
@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);
}
And the layout for the view:
<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>
Can anyone point out what I am doing wrong here? If this question has been answered before, could someone kindly give me a link? I couldn't seem to find any similar problems after searching. I'm developing for API 11 and testing on a Samsung Galaxy Tab 8.9 running Android 4.04.
Thanks!