在 LinearLayout 中對 ImageView 設定 android:layout_gravity="right" 卻無效果。
layout_gravity 控制子元件在父容器剩餘空間中的對齊。LinearLayout 為 horizontal 且子元件 layout_width="wrap_content",父容器會依序排列子元件,不會保留右側空間,故 gravity="right" 無處生效。LinearLayout 為 vertical,子元件預設佔滿寬度,layout_gravity="right" 才會生效(靠右對齊)。<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<View
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="1" /> <!-- 彈性佔位 -->
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_icon" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:src="@drawable/ic_icon" />
</LinearLayout>
<!-- RelativeLayout -->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:src="@drawable/ic_icon" />
</RelativeLayout>
<!-- ConstraintLayout -->
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_icon"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="end"> <!-- 父容器 gravity 控制所有子元件整體靠右 -->
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_icon" />
</LinearLayout>
| 屬性 | 作用對象 | 生效條件 |
|---|---|---|
android:gravity | 父容器 | 控制所有子元件在容器內的整體對齊 |
android:layout_gravity | 子元件 | 控制單一子元件在容器剩餘空間中的對齊 |
android:layout_weight | 子元件 | 分配剩餘空間比例,常用於佔位撐開 |
要在 LinearLayout 讓 ImageView 靠右,核心在於製造右側剩餘空間:用 weight 佔位、改 vertical 方向、或直接改用 ConstraintLayout。掌握 gravity vs layout_gravity 差異,佈局不再靠猜。