2013-05-14 72 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