相信很多学习了android的人,都知道布局中存在两个很相似的属性:android :layout_gravity和android:gravity。一般的都知道,
android :layout_gravity是表示该组件在父控件中的位置
android:gravity是表示该组件的子组件在自身中的位置
例子:
Xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="我在右边显示"
android:layout_gravity="right"
android:background="#00ff00"
/>
如上的代码显示效果如下:
经管很明了,但是某些时候也会出现失效的情况,如下:
Xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="我在右边显示"
android:layout_gravity="right"
android:background="#00ff00"
/>
如上代码效果如下:
Why?
第二段代码和第一段代码唯一的区别,线性布局中android:orientation="vertical"属性不存在,使用的是默认水平方向。也说明当为父布局的LinearLayout是android:orientation="vertical"的时候,android:layout_gravity="right"才会生效。
我们在定义一个控件默认的位置是在屏幕左上方,线性布局是存在两个方向的,既然当水平方向为垂直的时候是,android:layout_gravity="right"才会生效。那么当水平方向为默认的水平方向的时候,会不会对其他的属性有影响呢?答案是肯定的。既然左右为一对的话,那么上下似乎应该为一对。
经过测试当LinearLayout是android:orientation="horizontal"的时候,android:layout_gravity="bottom"才会生效。
不再一一验证其他属性,做一个简单的总结如下:
当作为父layout的LinearLayout的属性为androidrientation="vertical" 的时候,android:layout_gravity="?"这里设为横向的时候才能生效。比如:left,right,center_horizontal等
当作为父layout的LinearLayout的属性为androidrientation="horizental" 的时候,android:layout_gravity="?"这里设为纵向的时候才能生效。比如:top,bottom,center_vertical等;