Android LinearLayout填充宽度

时间:2011-06-03 16:44:35

标签: android android-linearlayout

我想知道为什么会这样:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="fill_parent"
    android:gravity="center_vertical"
    android:layout_height="wrap_content" android:layout_gravity="top"
    android:background="@drawable/gradient" android:focusable="true"
    android:paddingTop="5dip" android:paddingBottom="5dip"
    android:focusableInTouchMode="true">
        <EditText android:id="@+id/searchField"
            android:layout_width="wrap_content" android:layout_height="fill_parent"

            android:paddingTop="2dip" android:paddingBottom="2dip"
            android:paddingLeft="10dip" android:paddingRight="10dip"
            android:inputType="textVisiblePassword" android:radius="5dip"
            android:layout_marginLeft="10dip"
            android:background="@drawable/search_background" android:textColor="#000000" />

        <Button android:id="@+id/info" android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dip"
            android:background="@drawable/info_btn" />
</LinearLayout>

如果我将“fill_parent”设置为我的EditText的layout_width,它会占用父级的整个宽度,按钮会消失(我猜它隐藏在EditText下面)。

有人可以解释一下吗?我想让Button取自己的宽度,EditText取剩余的宽度。

1 个答案:

答案 0 :(得分:24)

你告诉EditText为fill_parent,因此它填满了屏幕(整个宽度,没有为你的按钮留出空间)。

您希望按钮包装其内容和编辑文本以填充余数,您可以使用layout_weight属性执行此操作:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:layout_gravity="top"
 android:gravity="center_vertical"
 android:paddingTop="5dip"
 android:paddingBottom="5dip"
 android:orientation="horizontal">
<EditText
    android:id="@+id/searchField"
    android:layout_width="0dip"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:layout_marginLeft="10dip"
    android:paddingTop="2dip"
    android:paddingBottom="2dip"
    android:paddingLeft="10dip"
    android:paddingRight="10dip"
    android:radius="5dip"
    android:inputType="textVisiblePassword"
    android:textColor="#000000" />
<Button
    android:id="@+id/info"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="10dip"
    android:text="Blah" />
</LinearLayout>

(我把你的可绘制参考文献用于其他人的通用)

另一方面,不要让你的XML在eclipse中看起来更整洁,更易于维护:

  

窗口&gt;偏好&gt; XML&gt; XML文件&gt;编辑

     

线宽120

     

拆分多个属性TICK

     

对齐最终括号UNTICK

     

在PCDATA UNTICK中保留空白标签

     

清除所有空行UNTICK

     

在关闭TICK之前插入空格

     

点击确定

然后你可以修复你的XML文件,当你打开一个XML文件CTRL + A然后CTRL + SHIFT + F将很好地格式化它!

相关问题