[英]Android: how to make a view grow to fill available space?
這似乎很簡單,但我無法弄清楚如何做到這一點。 我有一個帶有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>
布局的關鍵點是:
fill_parent
計算事物高度的高度時, fill_parent
考慮剩余空間,而不是它可能占用的所有空間如果沒有其他的東西 fill_parent
( match_parent
在2.2+中),因此它占用了剩余的可用空間 抱歉沒看過你的問題就夠了。 如果您想以垂直方式執行此操作,上面的代碼將提供答案。 對於水平布局,@ Sunun發布的代碼應該有效。
使用將layout_width
或layout_height
設置為0dp
(按要填充剩余空間的方向)。 然后使用layout_weight
使其填充剩余空間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.