一直對layout_weight屬性感到比較困惑,今天學習一下,來深刻了解layout_weight屬性和它的用法。android
首先,看看Android官方文檔是怎麼說的,畢竟人家纔是權威嘛。佈局
官方文檔的意思是:學習
layout_weight屬性用於分配LinearLayout中的的額外空間(extra space)。spa
若是View不想拉伸的話,layout_weight值設置爲0。不然的話這些像素會按比例分配到
code
這些weight值大於0的全部View。xml
換句話說,也就是android:layout_weight屬性告知LinearLayout如何進行子組件的佈置安排。blog
說這麼多,不如用幾個例子來形象的描述它:圖片
1.首先設置一個Linear_Layout佈局,方向設置爲水平,放置兩個TextView,不設置Layout_weight值。能夠看到文檔
空餘的白色部分就是官方文檔中所說的extra space(額外空間)。get
佈局文件代碼:
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="wrap_content" 5 android:orientation="horizontal" > 6 7 <TextView 8 android:layout_width="wrap_content" 9 android:layout_height="wrap_content" 10 android:background="#f00" 11 android:text="TextView1" /> 12 <TextView 13 android:layout_width="wrap_content" 14 android:layout_height="wrap_content" 15 android:background="#0f0" 16 android:text="ThisIsTextView2" 17 /> 18 </LinearLayout>
2.設置兩個TextView的Layout_weight的值都爲1。
在上面的xml文件中,給每一個TextView增長一個"android:layout_weight=1"屬性。
TextView1,TextView2的layout_weight值分別設置爲2和1,1和2,看運行的效果:
2和1:
1和2:
相信經過以上例子和圖片,你們應該對layout_weight屬性的用法已經很是理解了。
那麼,問題又來了。若是我想要將兩個子組件分配相同的寬度或高度,那該怎麼設置layout_weight呢?
只須要將各子組件的layout_width值設置爲0,這樣就避開了第一步的空間分配。
這樣LinearLayout就只會考慮使用layout_weight值來完成空間的分配了。
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="wrap_content" 5 android:orientation="horizontal" > 6 7 <TextView 8 android:layout_width="0dp"<!--將layout_width值設置爲0dp以避開第一步的空間分配--> 9 android:layout_height="wrap_content" 10 android:background="#f00" 11 android:layout_weight="1"<!--LinearLayout將會按此值分配空間--> 12 android:text="TextView1" /> 13 <TextView 14 android:layout_width="0dp" 15 android:layout_height="wrap_content" 16 android:background="#0f0" 17 android:layout_weight="1" 18 android:text="ThisIsTextView2" 19 /> 20 </LinearLayout>
但願這篇文章對你們有所幫助,若是喜歡,請推薦,謝謝~
若是轉載,請在文章開頭處註明本博客地址:http:www.cnblogs.com/JohnTsai
歡迎討論交流,郵箱:JohnTsai.Work@gmail.com