Android - RelativeLayout Start/End 與 Left/Right 的不同

在RelativeLayout的設計中, 一般來說Start = Left, End = Right

所以

android:layout_alignStart/End = android:layout_alignLeft/Right
android:layout_toStart/EndOf = android:layout_toLeft/RightOf

但以上規則只適用於讀法規則為由左而右開始的國家

如果讀法規則為由右開始的國家時, 會有以下的錯誤情況

XML的寫法使用 Left

.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<Button
android:id="@+id/button_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:text="1-Button" />

<Button
android:id="@+id/button_2"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_below="@+id/button_1"
android:layout_alignLeft="@+id/button_1"
android:text="2-Button" />
</RelativeLayout>

執行結果

這對由右而左的國家來說是很不習慣的, 因為應該是要以右邊來對齊才對

因此Android 在API 17 (Android 4.2) 提出了通用的法則 Start / End, 可適用於 由左而右或由右而左的國家

XML的寫法使用 Start

.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<Button
android:id="@+id/button_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:text="1-Button" />

<Button
android:id="@+id/button_2"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_below="@+id/button_1"
android:layout_alignStart="@+id/button_1"
android:text="2-Button" />
</RelativeLayout>

執行結果

Android - RelativeLayout Start/End 與 Left/Right 的不同

https://nickcarter9.github.io/2017/04/25/2017/2017_04_25-relativelayout_start_left_diff/

作者

Nick Lin

發表於

2017-04-25

更新於

2023-01-18

許可協議


評論