最近在写代码时,偶然发现发现RelativeLayout 的setGravity并不是完全按照预想的设置进行展示,所以有一点纠结,刚开始以为是写的有问题,后来进行了一些测试发现,这个Gravity属性的确存在一些问题.
测试1:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:color/holo_blue_bright"
android:gravity="bottom"
tools:context=".MainActivity">
<ImageView
android:id="@+id/id_img_down"
android:src="@mipmap/ad2_720"
android:layout_width="300px"
android:layout_height="400px"
/>
<ImageView
android:id="@+id/id_img_up"
android:src="@mipmap/ahtv"
android:layout_width="100px"
android:layout_height="100px"/>
</RelativeLayout>
预想1:两张ImageView都在 RelativeLayout 的底部
结果1:
之后又尝试用了alineg_botom 都有一些小问题(进行了很多测试,由于时间紧就不详细描述了)最后终于得到想要的效果:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:color/holo_blue_bright"
android:gravity="bottom"
tools:context=".MainActivity">
<ImageView
android:id="@+id/id_img_down"
android:src="@mipmap/ic_launcher"
android:layout_width="300px"
android:layout_height="400px"
/>
<ImageView
android:id="@+id/id_img_up"
android:src="@mipmap/ahtv"
android:layout_width="100px"
android:layout_height="100px"
android:layout_alignBottom="@+id/id_img_down"/>
</RelativeLayout>
后来在API文档上看到有这样一段介绍:
A Layout where the positions of the children can be described in relation to each other or to the parent.
Note that you cannot have a circular dependency between the size of the RelativeLayout and the position of its children. For example, you cannot have a RelativeLayout whose height is set to WRAP_CONTENT and a child set to ALIGN_PARENT_BOTTOM.
Note: In platform version 17 and lower, RelativeLayout was affected by a measurement bug that could cause child views to be measured with incorrect MeasureSpec values. (See MeasureSpec.makeMeasureSpec for more details.) This was triggered when a RelativeLayout container was placed in a scrolling container, such as a ScrollView or HorizontalScrollView. If a custom view not equipped to properly measure with the MeasureSpec mode UNSPECIFIED was placed in a RelativeLayout, this would silently work anyway as RelativeLayout would pass a very large AT_MOST MeasureSpec instead.
This behavior has been preserved for apps that set android:targetSdkVersion="17" or older in their manifest's uses-sdk tag for compatibility. Apps targeting SDK version 18 or newer will receive the correct behavior
所以RelativeLayout在设置重力位置的时候还是有很多坑的:
1 使用Gravity 如果RelativeLayout里面有两个View,那么Gravity就不会是预想的。
2 使用align要注意相应id的view大小,对自己view大小的影响
3 还有文档上说明的circular dependency及 RelativeLayout 被放到scrolling container时的测量问题