Android layout属性之gravity和layout_gravity

gravity用来描述当前view的内容在view中的位置。

例如
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="bottom"
        android:text="hello" />
那么hello就会出现在按钮的最下方。
 
如果当前view是个view group,例如
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="bottom" >
 
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="hello" />
 
</LinearLayout>
那按钮会出现在layout的最下方。对这个例子,也就是屏幕的最下方。
 
如果把button的宽高都改为match_parent
那对于
    <Button
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="bottom"
        android:text="hello" />
button跟layout一样大,hello是在该button的最下方。
对于
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="bottom" >
 
    <Button
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="hello" />
 
</LinearLayout>
因为现在button和layouty一样大,所以LinearLayout中的android:gravity没有实际显示效果。
另外,该属性无递归效果。
 
gravity是控制其内容或者包含的views在该view(或view group)中的位置。而layout_gravity是表示该view在其父容器view group中的位置。
该属性只在父容器是LinearLayout和FrameLayout时有效。
如果要实现button出现在LinearLayout的最下方(上面第二个例子),用layout_gravity可以这么写
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
     >
 
    <Button
        android:layout_gravity="bottom"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="hello" />
 
</LinearLayout>
 
只需要把LinearLayout中的android:gravity="bottom"删掉,然后再Button加入android:layout_gravity="bottom"
 
如果把上面例子中的android:orientation=”horizontal"改为vertical,那么button位置还是在上面。这是因为对于LinearLayout,如果是horizontal,则只能采用top,center,bottom等上下结构的属性控制纵向位置;如果是vertical,则只能控制横向位置。
 
与gravity一样,如果该view和父容器view group的大小一样,则该属性无实际效果。事实上通过wrap_content和match_parent,这种情况经常出现。所以经常发现gravity和layout_gravity无效的情况。这时就要检查是否是因为父子view大小相同了。
原文地址:https://www.cnblogs.com/xichengtie/p/3912171.html