要想讓您的控制項水平置中或垂直置中其實很簡單,只要在控制項的上一級中設定【android:gravity="center"】屬性即可
如:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:gravity="center" android:background="#000000" android:layout_width="fill_parent" android:layout_height="fill_parent" > <ImageView android:id="@+id/logo" android:src="@drawable/logo" android:layout_width="wrap_content" android:layout_height="wrap_content" /></LinearLayout>
這樣一個ImageView控制項就乖乖的待在你選定地區的正中間了。 gravity的屬性值還有很多,可以單獨設定水平或垂直置中。大家可以查看相應的文檔,或使用Eclipse的提示功能快速查看。
我們來看一個執行個體,如果你想實現這樣的布局,兩個按鈕置中,該怎樣做?
比較容易實現的是LinearLayout布局,當然如果換成RelativeLayout同樣也可以實現。
這裡簡單說一下用RelativeLayout布局如何?,首先需找中心點,然後以這個中心點為參照物即可實現。接下來看一下更容易實現的LinearLayout布局的實現。
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/start_server" android:text="Start" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/stop_server" android:text="Stop" /></LinearLayout>
如果現在需求改變了,中間只需要一個Button即可,那麼實現起來很簡單,只需要將上面的其中一個Button標籤刪除即可,但是有些人這麼去實現
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/start_server" android:layout_gravity="center" android:text="Start" /></LinearLayout>
這麼實現顯然不能置中,雖然在Button標籤指定了android:layout_gravity="center"但是貌似布局不領情,為啥?
原因很簡單,LinearLayout只能有一個方向,要麼Vertical,要麼Horizontal,完全不會領layout_gravity這個屬性的情,所以上面的實現只有這麼一個結果
如果改成水平方向的布局
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/start_server" android:layout_gravity="center" android:text="Start" /></LinearLayout>
會變成這樣的結果
按照上面的理論也就能想通了,所以android:layout_gravity="center"這個屬性雖然LinearLayout也具有,但是卻虛晃一槍,真正其作用的還是其本身的屬性android:gravity="center",當然如果想一探究竟,為啥不起作用,可以從LinearLayout這個布局的原始碼看起,這裡不再贅述。