1. 程式人生 > >Android 權重正確解釋以及解釋誤區分析

Android 權重正確解釋以及解釋誤區分析

1.首先宣告只有在Linearlayout中,layout_weight屬性才有效。

在這裡我們設定三個的權重比為 藍1:黃2:紅2那麼它的效果是不是 藍1:黃2:紅2呢

 <TextView
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
       android:background="@color/blue"
        />
    <TextView
        android:layout_weight="2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/yellow"
        />
    <TextView
        android:layout_weight="2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/red"
        />

 

然而實際的效果並不是藍1:黃2:紅2而是藍2:黃1:紅1大家是不是感覺這個安卓的權重是成反比呢這個效果的理解就是這樣,但是事實並不是這樣的

實際上它是用來指定(剩餘空閒空間)的分割比例,而非按比例分配整個空間。另外android:layout_weight會引起爭議,是因為在設定該屬性的同時, 設定android:layout_width為wrap_content和match_parent會造成兩種截然相反的效果。因為在這裡設定為match_parent是用了螢幕的寬度(假設螢幕的寬度為1080),所以三個顏色設定下來螢幕的閒散空間為-2160那麼按照剛才的筆記1080+(-2160*1/5)是不是就是最多的那份所以會造成一種反比的效果。

 

 

如果想用layout_weight平均分配空間,正確方式是將layout_width(或layout_height)設定為0dp或者設定為wrap_content,
      再通過layout_weight按比例分配空間

 關鍵點在於搞清楚什麼是剩餘空閒空間