Android中gravity与layout_gravity的使用区别

来源:互联网 发布:淘宝网那里卖包包拉链 编辑:程序博客网 时间:2024/05/18 12:43

LinearLayout有两个非常相似的属性:android:gravity与android:layout_gravity。

android:gravity 属性是对该view中内容的限定(设置的是控件自身上面的内容位置).比如一个button 上面的text. 你可以设置该text 相对于view的靠左,靠右等位置.
android:layout_gravity  是用来设置该view相对与父view 的位置(设置控件本身相对于父控件的显示位置).比如一个button 在linearlayout里,你想把该button放在linearlayout里靠左、靠右等位置就可以通过该属性设置. 

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:paddingLeft="16dp"    android:paddingRight="16dp"    android:orientation="vertical" >    <EditText        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:hint="@string/to" />    <EditText        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:hint="@string/subject" />    <EditText        android:layout_width="fill_parent"        android:layout_height="0dp"        android:layout_weight="1"        android:gravity="top"        android:hint="@string/message" />    <Button        android:layout_width="100dp"        android:layout_height="wrap_content"        android:layout_gravity="right"        android:text="@string/send" /></LinearLayout>



注:

当 android:orientation="vertical" 时, 只有水平方向的设置才起作用,垂直方向的设置不起作用。即:left,right,center_horizontal 是生效的。

当 android:orientation="horizontal" 时, 只有垂直方向的设置才起作用,水平方向的设置不起作用。即:top,bottom,center_vertical 是生效的。
因为对于LinearLayout来说,orientation就已经决定了内部的排列方式,否则的话,用RelativeLayout就可以了。


0 0
原创粉丝点击