以下兩個佈局文件產生不同的結果:不對稱RelativeLayout的行爲
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<View
android:id="@+id/box"
android:background="#ff0000"
android:layout_width="0dp"
android:layout_height="30dp"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/next_box" />
<View
android:id="@+id/next_box"
android:background="#0000ff"
android:layout_width="60dp"
android:layout_alignParentRight="true"
android:layout_height="30dp"
/>
</RelativeLayout>
</LinearLayout>
結果:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<View
android:id="@+id/box"
android:background="#ff0000"
android:layout_width="0dp"
android:layout_height="30dp"
android:layout_alignParentLeft="true"
/>
<View
android:id="@+id/next_box"
android:background="#0000ff"
android:layout_width="60dp"
android:layout_alignParentRight="true"
android:layout_height="30dp"
android:layout_toRightOf="@+id/box"
/>
</RelativeLayout>
</LinearLayout>
結果:
兩個佈局試圖描述相同的限制。也就是說,紅色矩形應觸摸父項的左邊緣,藍色矩形應該觸摸父項的右邊緣,並且它們應該水平相鄰。唯一的區別是您是否在紅色矩形或藍色矩形上指定了「next to」約束。我找出了與通過形成約束的依賴圖生成的度量解析順序有關的原因,但我只是通過閱讀RelativeLayout的源代碼來計算出來的,並且我找不到有關此行爲的任何文檔/註釋。由於RelativeLayout必須是常用的佈局組件,對此行爲是否有更直觀的解釋,或者是否存在我缺少的某些文檔部分?
您已設置'layout_width' attri bute或第一個「視圖」爲0.在第一種情況下,「RelativeLayout」明確地給出了剩餘寬度,因爲您已經定義了它的左右對齊。在第二種情況下,沒有定義右對齊,因此左邊的佈局爲0寬度,另一個「視圖」佔用所有可用寬度,因爲它明確定義爲與第一個「視圖」的右邊界對齊'。 – corsair992