这看起来很简单,但我不知道该怎么做。我有一个带有 EditText 和两个 ImageButtons 的水平布局。我希望 ImageButtons 具有固定大小,并且 EditText 占用布局中的剩余空间。如何实现?
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
<ImageButton
android:src="@drawable/img1"
android:layout_width="50dip"
android:layout_height="50dip">
</ImageButton>
<ImageButton
android:src="@drawable/img2"
android:layout_width="50dip"
android:layout_height="50dip">
</ImageButton>
</LinearLayout>
如果您想保持布局相同(即文本后面的按钮),请使用 layout_weight
属性和 fill_parent
,因此:
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<EditText
android:layout_weight="1"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</EditText>
<ImageButton
android:src="@drawable/img1"
android:layout_width="50dip"
android:layout_height="50dip">
</ImageButton>
<ImageButton
android:src="@drawable/img2"
android:layout_width="50dip"
android:layout_height="50dip">
</ImageButton>
</LinearLayout>
赋予 EditText
'权重' 使其最后被计算出来并优先于按钮。玩不同的 layout_weights,看看你能有多少乐趣!
在相对布局中试试这个
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ImageButton
android:id="@+id/btn1"
android:src="@drawable/icon"
android:layout_width="50dip"
android:layout_height="50dip"
android:layout_alignParentRight="true"/>
<ImageButton
android:id="@+id/btn2"
android:src="@drawable/icon"
android:layout_width="50dip"
android:layout_height="50dip"
android:layout_toLeftOf="@+id/btn1"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toLeftOf="@+id/btn2">
</EditText>
</RelativeLayout>
好的:
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ImageButton
android:id="@+id/button1"
android:src="@drawable/img1"
android:layout_width="50dip"
android:layout_alignParentTop="true"
android:layout_height="50dip">
</ImageButton>
<ImageButton
android:src="@drawable/img2"
android:layout_width="50dip"
android:layout_alignParentTop="true"
android:layout_toRightOf="@id/button1"
android:layout_height="50dip">
</ImageButton>
<EditText
android:layout_below="@id/button"
android:layout_width="wrap_content"
android:layout_height="fill_parent">
</EditText>
</RelativeLayout>
布局的关键点是:
固定大小的项目首先放置在布局中,这样当Android在文件中稍后使用fill_parent计算事物的高度时,它只考虑剩余空间,而不是它可能占用的所有空间如果没有别的东西
EditText 的高度为 fill_parent(2.2+ 中为 match_parent),因此它占用了剩余的可用空间
抱歉,没有阅读您的问题。如果您想以垂直方式进行操作,上面的代码提供了答案。对于水平布局,@Sunil 发布的代码应该可以工作。
使用将 layout_width
或 layout_height
设置为 0dp
(按您要填充剩余空间的方向)。然后使用 layout_weight
使其填充剩余空间。
我在填充 LinearLayout 时遇到了类似的问题(我正在使用 Artic Fox 版本)。在我的设计中,我在具有垂直方向的 LinearLayout 中有 2 个按钮。就我而言,我通过放置以下内容来解决问题:
android:insetBottom="0dp"
android:insetTop="0dp"
不定期副业成功案例分享