Android 并排编辑文本和按钮

Android 并排编辑文本和按钮,android,android-layout,user-interface,Android,Android Layout,User Interface,我想在我的布局中显示一个EditText和一个按钮并排显示,它们之间有一个小空间(边距)。我不想设定一个固定的尺寸(我认为这是一个坏习惯) 怎么做 我的尝试: <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <EditText android:layout_width="match_parent" android:layout_

我想在我的布局中显示一个
EditText
和一个
按钮
并排显示,它们之间有一个小空间(边距)。我不想设定一个固定的尺寸(我认为这是一个坏习惯)

怎么做

我的尝试:

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="left"
    android:layout_alignParentLeft="true" />

<Button
    android:id="@+id/btn_search"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_gravity="right" 
    android:text="Search" />
 </RelativeLayout>

您正在使用一个
相对值;但是,您不能在该类型的
视图组中创建灵活的设计。必须使用
线性布局

我们使用
android:layout\u weight=“1”
android:layout\u width=“0dp”
来创建一个灵活的控件。根据不同的尺寸比例调整重量编号

之后,我们在两个控件上使用
android:layout_margin
,这样每个控件的加权大小就相等了

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <EditText
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:layout_marginRight="8dp" />

    <Button
        android:id="@+id/btn_search"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="Search"
        android:layout_marginLeft="8dp" />
</LinearLayout>

使用线性布局并排显示,并适当使用“匹配父项”和“包装内容”

下面是一段xml代码

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical" >

    <EditText
        android:id="@+id/et"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/go"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Go!!" />

</LinearLayout>

您可以使用水平方向的线性布局,并按以下方式添加编辑文本和按钮

<LinearLayout
orientation="horizontal"
layoutwidth="match_parent"
layoutheight="wrap_content">

<EditText
layoutwidth="0dp"
layoutheight="wrap"
layout_weight=".8"/>

<Button
layoutwidth="0dp"
layoutheight="wrap"
layout_weight=".2"/>

</LinearLayout>

希望这能解决你的问题。确保根据需要更改重量

谢谢