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的最下方。
對於
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大小相同了。