android 高度上分权重,Android LinearLayout weight权重使用
在日常的開發過程中,我們通常或多或少會使用到LinearLayout的weight屬性來進行權重設置,進而達到按比例顯示布局的意圖
通常我們在使用時,會這樣使用
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:background="@android:color/holo_blue_light" />
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@android:color/holo_red_light" />
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@android:color/holo_green_light" />
權重示例.png
我們一般使用weight屬性時,會將width或者height設置為0dp,這時控件的寬或者高就會按照我們設置的權重,如上面的2:1:1來填充父控件
但是,如果子控件的寬度或高度不設置成0dp,那么他們的寬高是怎么分配的呢?
我們首先明確一點:weight權重是針對于LinearLayout的剩余空間,所以我們在設置該屬性之后,LinearLayout會計算自己的剩余空間,然后將剩余空間按權重分配到子控件上。
以橫向布局為例:
LinearLayout的剩余空間 = LinearLayout的寬度 - 各個子控件的寬度,可以有負值
以2個子控件為例,權重分別為2和1
那么
子控件1的寬度 = 子控件1的初始寬度 +(2/3)* LinearLayout的剩余空間
子控件2的寬度 = 子控件2的初始寬度 +(1/3)* LinearLayout的剩余空間
我們來驗證一下:
為方便測量,使用px單位, 我們先設定父控件寬 = 800px, 子控件1 = 200px 子控件2 = 100px,weight都為1,我們自己先算一下,可以得出:
LinearLayout的剩余空間 = 800 - 200 - 100 = 500
子控件1寬度 = 200 + (1/2) * 500 = 450
子控件2寬度 = 100 + (1/2) * 500 = 350
看下效果是否和我們計算的一致:
android:layout_width="800px"
android:layout_height="match_parent"
android:orientation="horizontal">
android:layout_width="300px"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@android:color/holo_blue_light" />
android:layout_width="100px"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@android:color/holo_red_light"
android:singleLine="true" />
權重示例1.png
和我們預期的一致
我們再檢測下"match_parent"的情況:
設定父控件寬 = 600px, 子控件1 ="match_parent" weight = "1" 子控件2 = "match_parent" weight = "2",我們自己先算一下,可以得出:
LinearLayout的剩余空間 = 600- 600- 600= -600
子控件1寬度 = 600+ (1 / 3) * (-600)= 400
子控件2寬度 = 600+ (2 / 3) * (-600)= 200
看下效果是否和我們計算的一致:
android:layout_width="600px"
android:layout_height="match_parent"
android:orientation="horizontal">
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@android:color/holo_blue_light" />
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="2"
android:background="@android:color/holo_red_light"
android:singleLine="true" />
權重示例2.png
和我們計算的完全一致
子控件"wrap_content"與確定值計算方式同上,有空的可以驗證下
另外需要注意一點:weight是float類型
總結
以上是生活随笔為你收集整理的android 高度上分权重,Android LinearLayout weight权重使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: oracle判断是否是手机号码,orac
- 下一篇: boa php5.5 移植,BOA+PH