問題代碼
<LinearLayout android:orientation="horizontal" ...>
<ImageView ... />
<EditText
android:layout_alignParentRight="true" <!-- LinearLayout 無效屬性 -->
android:gravity="right" />
</LinearLayout>
方案一:RelativeLayout
<RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content">
<ImageView
android:id="@+id/logo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true" />
<EditText
android:layout_width="134dp"
android:layout_height="35dp"
android:layout_toRightOf="@id/logo"
android:layout_alignParentRight="true"
android:gravity="right" />
</RelativeLayout>
方案二:LinearLayout + layout_gravity + weight
<LinearLayout android:orientation="horizontal" android:weightSum="1">
<ImageView android:layout_width="0dp" android:layout_weight="0.3" ... />
<EditText
android:layout_width="0dp"
android:layout_weight="0.7"
android:gravity="right" />
</LinearLayout>
關鍵區別
android:gravity:控制視圖內容對齊(文字靠右)。
android:layout_gravity:控制視圖在父佈局中的位置(需父佈局支持,如 LinearLayout、FrameLayout)。
layout_alignParentRight 僅在 RelativeLayout 生效。