Android layout属性之gravity和layout_gravity

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

例如
    <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"
    xmlns:tools=" http://schemas.android.com/tools"
    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"
    xmlns:tools=" http://schemas.android.com/tools"
    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大小相同了。
相关文章
相关标签/搜索