標籤:
首先來查看android sdk文檔,有這麼一段話
LinearLayout also supports assigning a weight to individual children with the android:layout_weight attribute. This attribute assigns an "importance" value to a view in terms of how much space is should occupy on the screen. A larger weight value allows it to expand to fill any remaining space in the parent view. Child views can specify a weight value, and then any remaining space in the view group is assigned to children in the proportion of their declared weight. Default weight is zero.
我們從文檔中可以看出LinearLayout中子控制項可以使用layout_weight 屬性來分配所佔的“權重”,但是實際使用的過程中,經常會出錯,會讓人感到疑惑,下面是自己總結的一些經驗:
以水平(垂直方向類似)LinearLayout為例:
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="16dp" android:layout_marginRight="16dp" ><Button android:id="@+id/crime_date" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" /><CheckBox android:id="@+id/crime_solved" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="@string/crime_solved_label" /></LinearLayout>
LinearLayout是個水平線性布局,會根據每個子成員layout_width和layout_weight來決定應該給他們分配多少空間, 遵循以下規則:
- 首先根據layout_width的值來初步指定空間,因為layout_width都是wrap_content, 那布局管理器會分別給兩個子控制項足夠的空間來用於水平方向的展開,結果就是下面圖片:
- 然後,因為水平方向上仍然有足夠的空間,那麼布局管理器就會將這個多餘的控制項按照layout_weight的值進行分配。上面的例子中是1:1,那麼會將多餘控制項按照1:1的比例分配,那效果就變成了:
- 如果想給兩個控制項設定為寬度相同,Android推薦的做法是將兩個控制項的屬性這麼設定:layout_width=0dp, layout_weight=1
- 如果一個控制項沒提供layout_weight,那麼android會預設其為0
- 由於不同的程式員有不同的寫代碼的慣例,android允許layout_weight的值是小數或整數,分配比例就是各自(layout_weight值)/(各自的layout_weight相加的值),這條規則成立的前提是LinearLayout沒有設定android:weightSum來限制總和。
來再看一個經常讓人誤解的例子:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_height="wrap_content" android:text="small" android:textColor="#02F" android:layout_width="wrap_content" android:layout_weight="1" /> <TextView android:layout_height="wrap_content" android:textColor="#F20" android:text="A very very long text that needs to wrap.A very very long" android:layout_width="wrap_content" android:layout_weight="1" /></LinearLayout>
它的效果是這樣:
它並沒有按照weight去1:1的分配空間比例,這是因為布局管理器按照第一條規則滿足了layout_width=’wrap_content’,這種情況下,如果確實想按照1:1的空間來分配,就只能設定layout_width=’0dp”, 這樣做的效果就是這樣:
歡迎斧正
Android UI: LinearLayout中layout_weight 屬性的使用規則