当我在同一“行”有两个视图时,Android如何计算视图的大小,一个宽度=“fill_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
答案 0 :(得分:7)
android:layout_toLeftOf="@+id/Button01"
会强制EditText
的右边界与Button
的左侧对齐,因此Android会忽略match_parent
宽度,迫使宽度仅填充从左侧父母一侧到按钮右侧。
android:layout_toRightOf="@+id/EditText01"
会强制Button
的左边界与EditText
的右边对齐,但由于EditText
的宽度为match_parent
权限侧与父视图的右侧对齐,Android将强制该按钮离开屏幕。
答案 1 :(得分:1)
在两个示例中,<EditText/>
适合所有屏幕宽度。在第一个示例中,Button
不依赖于<EditText/>
,因此它可以与屏幕的右边缘对齐。然而,在第二个例子中,Button
必须与`的右边对齐,这就是它被推出视图的原因。
答案 2 :(得分: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/>