Android RelativeLayout和子元素的layout_width="match_parent"

4

当我在同一“行”上有两个视图,其中一个宽度为“fill_parent”时,Android如何计算视图的大小?

例如:

<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
3个回答

7
android:layout_toLeftOf="@+id/Button01"会将EditText的右边界强制对齐到Button的左侧,因此Android会忽略match_parent的宽度,强制宽度仅填充从父视图左侧到按钮右侧。 android:layout_toRightOf="@+id/EditText01"会将Button的左边界强制对齐到EditText的右侧,但由于EditTextmatch_parent宽度,因此右侧与父视图的右侧对齐,Android会将按钮强制移出屏幕。

将来你可以回来点赞 :) 不客气 - TronicZomB

1
在您的两个示例中,<EditText/> 占据了整个屏幕宽度。在第一个示例中,Button 不依赖于 <EditText/> ,因此可以与屏幕右边缘对齐。但是,在第二个示例中,Button 必须与“`”的右侧对齐,这就是为什么它被推出视图的原因。

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/>

是的,我知道RelativeLayout没有行;这就是引号的原因。我想知道match_parent是如何工作的,而不是一个具体的解决方案。谢谢。 - juan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接