[英]How does 'weight' make an element fill available space in an Android layout?
這是我第一次嘗試使用Android應用程序。 請原諒所有的無知和愚蠢。
如果您為所有元素分配該屬性的值,那么weight
是如何工作的。 然后, LinearLayout
重是唯一具有權重的元素時, weight
如何使ListView
填充LinearLayout
兩個元素之間的所有可用空間?
我有一個簡單的布局,其頂部為ListView
,屏幕底部為EditText
,'Button , and
TextView . Only the
. Only the
ListView and
TextView have
weight屬性(許多屬性(如邊距等),為簡潔起見,省略了僅具有默認屬性的元素):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerHorizontal="true"
android:orientation="vertical"
android:weightSum="10">
<ListView
android:id="@+id/files_list"
android:background="@drawable/text_view_border"
android:layout_height="0dp"
android:layout_weight="7.99"
...
android:soundEffectsEnabled="true" />
<TextView
android:id="@+id/result_text"
...
android:layout_width="fill_parent"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_height="wrap_content"
android:layout_weight="0.43"
android:gravity="center" />
</LinearLayout>
現在,這如何使ListView
填充碎石上的可用空間? 我本以為height=*
或類似的東西可以做到。 而“ 0.43” +“ 7.99”不太接近weightsome="10"
只會增加我的困惑。
在這種情況下,您無需使用weightSum
。 如果您只希望視圖占用一部分可用空間而不是全部占用, weightSum
更為有用。 如果從result_text
刪除權重,並從LinearLayout
刪除weightSum
,則它將按預期工作。 您還可以將files_list
的layout_weight
設置為更好的數字,例如1
。
從文檔 :
定義最大重量總和。 如果未指定,則通過將所有子項的layout_weight相加來計算總和。 例如,可以通過給它一個0.5的layout_weight並將weightSum設置為1.0來給單個孩子提供總可用空間的50%。
必須為浮點值,例如“ 1.2”。
應該這樣做:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerHorizontal="true"
android:orientation="vertical">
<ListView
android:id="@+id/files_list"
android:background="@drawable/text_view_border"
android:layout_height="0dp"
android:layout_weight="1"
...
android:soundEffectsEnabled="true" />
<TextView
android:id="@+id/result_text"
...
android:layout_width="fill_parent"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_height="wrap_content"
android:gravity="center" />
</LinearLayout>
與android:layout_width =“ match_parent”一起使用fill_parent。 這將填滿屏幕寬度的所有空間。 在最新版本的android中,不再使用fill_parent
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.