Android 布局學習之——LinearLayout的layout_weight屬性
一直對layout_weight屬性感到比較困惑,今天學習一下,來深入瞭解layout_weight屬性和它的用法。 定義 首先,看看Android官方文檔是怎麼說的,畢竟人家才是權威嘛。 官方文檔的意思是: layout_weight屬性用於分配LinearLayout中的的額外空間(extra space)。 如果View不想展開的話,layout_weight值設定為0。否則的話這些像素會按比例分配到 這些weight值大於0的所有View。 換句話說,也就是android:layout_weight屬性告知LinearLayout如何進行子組件的布置安排。 例子 說這麼多,不如用幾個例子來形象的描述它: 1.首先設定一個Linear_Layout布局,方向設定為水平,放置兩個TextView,不設定Layout_weight值。可以看到 空餘的白色部分就是官方文檔中所說的extra space(額外空間)。 複製代碼 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,看啟動並執行效果: 相信通過以上例子和圖片,大家應該對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>