2013-05-14 59 views
4

當我有兩個視圖在同一個「行」,一個寬度=「fill_parent」時,Android如何計算視圖的大小?Android RelativeLayout和childs with layout_width =「match_parent」

例子:

<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_height="fill_parent" 
    android:layout_width="fill_parent"> 
    <EditText 
     android:id="@+id/EditText01" 
     android:hint="Enter some text..." 
     android:layout_alignParentLeft="true" 
     android:layout_width="match_parent" 
     android:layout_toLeftOf="@+id/Button01" 
     android:layout_height="wrap_content"></EditText> 
    <Button 
     android:id="@+id/Button01" 
     android:text="Press Here!" 
     android:layout_width="wrap_content" 
     android:layout_alignParentRight="true" 
     android:layout_height="wrap_content"></Button> 
</RelativeLayout> 

這個代碼給所有自由空間的EditText並顯示按鈕,他的權利。但有了這個改變的EditText填滿了所有寬度和按鍵在屏幕的:

<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_height="fill_parent" 
    android:layout_width="fill_parent"> 
    <EditText 
     android:id="@+id/EditText01" 
     android:hint="Enter some text..." 
     android:layout_alignParentLeft="true" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content"></EditText> 
    <Button 
     android:id="@+id/Button01" 
     android:text="Press Here!" 
     android:layout_width="wrap_content" 
    android:layout_toRightOf="@+id/EditText01" 
     android:layout_height="wrap_content"></Button> 
</RelativeLayout 

回答

7

android:layout_toLeftOf="@+id/Button01"將強制對齊到Button左側約束EditText的權利,因此Android的忽略match_parent寬度強制寬度僅從左側父邊到按鈕的右側填充。

android:layout_toRightOf="@+id/EditText01"將強制約束Button的以對齊到EditText的右側的左側,但由於EditTextmatch_parent寬度權利側對準父視圖的右側和Android只會迫使按鈕關閉屏幕。

+0

謝謝,現在我明白了。我不能投票給你:( – juan 2013-05-14 20:17:12

+0

在未來,你可以回來和upvote :),不客氣 – TronicZomB 2013-05-14 20:18:54

1

在這兩個示例中,<EditText/>都適合屏幕的所有寬度。在第一個例子中,Button不依賴於<EditText/>,所以它可以對齊到屏幕的右邊緣。然而,在第二個例子中,Button必須與`右邊對齊,這就是爲什麼它被推出視圖。

+0

謝謝,現在我明白了。我不能投票給你:( – juan 2013-05-14 20:17:28

0

如果您使用的是RelativeLayout,那麼您沒有「行」,您擁有的所有空間都是可以排列視圖的空間。如果你想保持按鈕在屏幕的右側部分,並用EditText填充屏幕的其餘部分,你可以這樣做:

<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_height="fill_parent" 
    android:layout_width="fill_parent"> 
    <EditText 
     android:id="@+id/EditText01" 
     android:hint="Enter some text..." 
     android:layout_toLeftOf="@+id/Button01" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content"></EditText> 
    <Button 
     android:id="@+id/Button01" 
     android:text="Press Here!" 
     android:alignParentRight="true" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content"></Button> 
</RelativeLayout/> 
+0

是的,我知道RelativeLayout沒有行;這就是引用的原因,我想知道match_parent是如何工作的,而不是具體的解決方案。 – juan 2013-05-14 20:18:32