Android中 android:layout_weight 屬性

 Android佈局中 android:layout_weight 屬性解釋

定義:所有View(視圖)元素中都有一個XML屬性android:layout_weight,其值爲0,1,2,3...等整數值。
            使用了之後,其對應界面中的元素比例就會發生變化,變大或者變小。layout_weight屬性其實就是一個元素重要度的屬性,用於在線性佈局中爲不同的view元素設置不同的重要度。




 




<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android
     android:orientation="vertical" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent"  > 

 <TextView    android:id="@+id/a1" 
     android:layout_width="fill_parent"  
     android:layout_height="wrap_content"  
     android:text="" 
     android:layout_weight="1"  /> 
 <TextView    android:id="@+id/a2" 
     android:layout_width="fill_parent"  
     android:layout_height="wrap_content"  
     android:text="" 
     android:layout_weight="2"  /> 

 </LinearLayout> 

 歡迎各位朋友,一起來討論Android方面的技術難點。

 android:layout_weight屬性主要用來設置控件在屏幕上的位置空間,代碼中如果第一個TextView中爲1,第二個TextView爲2,則這兩個控件一個佔總空間的1/3,

 另一個佔總空間的2/3。


 在一個LinearLayout內各個組件是按weight值以正比形式顯示在屏幕上 ,而在LinearLayout之間以反比的形式顯示在屏幕上  ,很奇怪吧。




 官方文檔關於這個屬性的解釋

 LinearLayout  also supports assigning aweight to individual children. This attribute assigns an"importance" value to a view, and allows it to expand to fill anyremaining   space in the parent view. Child views can specify aninteger weight value, and then any remaining space in the viewgroup is assigned to children in the proportion of their    declaredweight. Default weight is zero. For example, if there are threetext boxes and two of them declare a weight of 1, while the otheris given no weight (0), the third text   box without weight will notgrow and will only occupy the area required by its content. Theother two will expand equally to fill the space remaining after allthree boxes are measured. If the third box is then given a weightof 2 (instead of 0), then it is now declared "more important" thanboth the others, so it gets half the total remaining space, whilethe first two share the rest equally.


 其實很簡單,weight本來的意思就是重量,即這個屬性所代表的是重要程度,而不是比例

 解釋:
 如果三個view水平排列,前兩個view的wieght是1,第三個是默認值0,(所有的視圖都有一個layout_weight值,其默認值爲0,)表示視圖多大就佔據多大的屏幕空間。可見第三個view的weight最低,那麼第三個view就只會佔用自己內容所需的寬度,剩下的寬度會被前兩   個view平分。

 如果第三個view的wieght是2,那麼前兩個view就會平分剩餘的寬度,而第三個會(gets half  the total) 佔據所有空間的一半。

 至於Linearlayout的weight屬性越小的所佔空間越多,我覺得這是因爲Linearlayout的默認高度問題,一個簡單的實驗當我把兩個Linearlayout的值設爲1和5的時候,屏幕比例  依然不變,因爲第一個Linearlayout的默認大小就是那麼大


很亂,這個東西,不好解釋。
發佈了47 篇原創文章 · 獲贊 25 · 訪問量 42萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章