RelativeLayout 中兩個 TextView 想分別對齊 Button 左上角、右上角,但使用 layout_alignLeft="@id/button1" 導致 TextView 貼著 Button 左邊緣而非父容器左側。
<RelativeLayout ...>
<TextView android:id="@+id/tv2" android:layout_alignLeft="@id/button1" /> <!-- 錯誤:對齊 Button 左邊 -->
<TextView android:id="@+id/tv1" android:layout_alignRight="@id/button1" /> <!-- 錯誤:對齊 Button 右邊 -->
<Button android:id="@+id/button1" ... />
</RelativeLayout>
針對**父容器 (RelativeLayout)** 邊緣對齊:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/tvLeft"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true" <!-- 關鍵:父容器左邊 -->
android:layout_above="@id/button1"
android:layout_marginBottom="4dp"
android:text="Left" />
<TextView
android:id="@+id/tvRight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true" <!-- 關鍵:父容器右邊 -->
android:layout_above="@id/button1"
android:layout_marginBottom="4dp"
android:text="Right" />
<Button
android:id="@+id/button1"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Button" />
</RelativeLayout>
| 屬性 | 參考對象 | 效果 |
|---|---|---|
layout_alignParentLeft="true" | 父容器 | View 左邊緣對齊父容器左邊緣 |
layout_alignLeft="@id/view" | 指定 View | View 左邊緣對齊指定 View 左邊緣 |
layout_toLeftOf="@id/view" | 指定 View | View 右邊緣靠指定 View 左邊緣 |
layout_above="@id/view" | 指定 View | View 底部靠指定 View 頂部 |
RelativeLayout rl = new RelativeLayout(this);
Button btn = new Button(this);
btn.setId(View.generateViewId());
RelativeLayout.LayoutParams btnParams = new RelativeLayout.LayoutParams(
dp(200), RelativeLayout.LayoutParams.WRAP_CONTENT);
btnParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
rl.addView(btn, btnParams);
TextView tvLeft = new TextView(this);
tvLeft.setText("Left");
RelativeLayout.LayoutParams leftParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
leftParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
leftParams.addRule(RelativeLayout.ABOVE, btn.getId());
leftParams.bottomMargin = dp(4);
rl.addView(tvLeft, leftParams);
TextView tvRight = new TextView(this);
tvRight.setText("Right");
RelativeLayout.LayoutParams rightParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
rightParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
rightParams.addRule(RelativeLayout.ABOVE, btn.getId());
rightParams.bottomMargin = dp(4);
rl.addView(tvRight, rightParams);
alignLeft/Right/Top/Bottom 參考**兄弟 View 邊緣**,alignParentLeft/Right/Top/Bottom 參考**父容器邊緣**,切勿混淆。View.generateViewId()。RelativeLayout 邊緣對齊核心:alignParent* 對齊父容器,align* 對齊兄弟,搞清參考系,佈局不再錯位。