我想知道为什么会这样:
<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 有剩余的宽度。
最佳答案
您告诉 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>
(我把你的 drawable references 拿出来让它对其他人通用)
一方面不要让您的 XML 在 Eclipse 中看起来更整洁且更易于维护:
Window > Preferences > XML > XML Files > Editor
Line width 120
Split multiple attributes TICK
Align final bracket UNTICK
Preserve Whitespace tags in PCDATA UNTICK
Clear all blank lines UNTICK
Insert Whitespace before closing TICK
Click ok
然后您可以修复您的 XML 文件,当您打开一个 XML 文件时,CTRL+A 然后 CTRL+SHIFT+F 将很好地格式化它!
关于Android LinearLayout 填充宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6230105/