1.LinearLayout(線性布局)
如果是要把imagebutton之類的控件居中對齊的話,要用android:layout_gravity 代碼如下:
<LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_gravity="center_horizontal" > <ImageView android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:src="@drawable/ic_mytce" /> </LinearLayout>
如果是textview之類文本控件就不能像上面那樣設置了,要用android:gravity="center", 這個用於文本對齊
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:id="@+id/text_02" android:layout_width="50dp" android:layout_height="50dp" android:background="#ff654321" android:gravity="center" android:layout_above="@id/text_01" android:layout_centerHorizontal="true" android:text="2"/> </RelativeLayout>
5.TableLayout(表格布局)
暫時沒使用過,就不說了。
<LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" android:layout_marginTop="8dp" android:textColor="#3A3C3B" android:textSize="14dp" android:text="版本號1.0" /> </LinearLayout>
2.FrameLayout(單幀布局)
因為它的特證就是,所有的子元素都只會顯示窗口的左上角,而且下一個子元素會覆蓋上一個子元素,所以理論上控件是不可以居中的;只有在textview文本控件的情況下可文本局中;
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#ff000000" android:gravity="center" android:text="1"/> </FrameLayout>
3.AbsoluteLayout(絕對布局)
它要定位就要確定絕對的x,y的坐標,如果你能獲取到你手機屏幕的像素值,它用起來還是很好的
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:layout_width="50dp" android:layout_height="50dp" android:background="#fffedcba" android:gravity="center" android:layout_x="125dp" android:layout_y="125dp" android:text="3"/> </AbsoluteLayout>
4.RelativeLayout(相對布局)
這個我個人很喜歡,很靈活,用得也很多;它指定居中非常簡單,直接android:layout_centerHorizontal="true"就行了