Button 設定 android:layout_gravity="center" 但不置中,且 Eclipse 提示無此屬性。
layout_gravity 屬於 LinearLayout.LayoutParams,**只有在 LinearLayout 子視圖時才生效**。若父佈局為 RelativeLayout、FrameLayout、ConstraintLayout 等,會被忽略。
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="test" />
</LinearLayout>
若 Button 本身寬度為 match_parent,想讓**文字**置中:
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="test" />
<RelativeLayout ...>
<Button
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="test" />
</RelativeLayout>
| 屬性 | 作用對象 | 生效條件 |
|---|---|---|
layout_gravity | 子視圖在父佈局中的位置 | 父佈局為 LinearLayout |
gravity | 視圖內容(文字、子元素)位置 | 視圖本身(如 Button、TextView、LinearLayout) |
layout_centerInParent | 子視圖置中於父佈局 | 父佈局為 RelativeLayout |