android 高度上分权重,安卓自适应布局(关于权重weight的使用技巧!)
weight和weightSum
Layout Weight
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 it 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.
大體意思就是,android:layout_weight 這個屬性代表了一個“重要性”的值,這個值的大小代表了該控件能在屏幕中占據多大的空間。這個值越大,表明該控件可以在父控件中占據較多的“ 剩余 ”空間。默認的weight是0。
在這里,大家一定要注意“ 剩余 ”兩個字!大家往往容易忽略這一點,導致出現了很多問題。舉個例子:水平方向布局的父類有三個子類,父類總的寬度是100,子類的寬度分別是10,20,30。 那么 android:layout_weight 這個屬性的目的,就是瓜分剩余的 100 - 10 - 20 - 30,也就是剩余的40的使用權。沒錯! 就是android:layout_weight 這個屬性 僅僅決定 哪個子類能瓜分到更多的40的部分!
android:weightSum
Defines the maximum weight sum. If unspecified, the sum is computed by adding the layout_weight of all of the children.
這個就很好理解了,weightSum定義了weight 總和的最大值。如果 android:weightSum 沒有定義,那么默認值就是通過各個子類的 layout_weight 累加得到。
例子:
效果:
內部的計算原理是:
Button的寬度 = Button 的 width + Button的weight * 父布局(LinearLayout)的寬度 / weightSum
上面的例子,也就是 Button的寬度 = 0 + 0.5 * LinearLayout的寬度 / 1 = 0.5 * LinearLayout的寬度
也就是Button的寬度將占屏幕的一半。
注意:
在布局文件中的控件,寬高設置成0、固定值、wrap和fill時使用”weight”屬性來調整大小的效果是有區別的
當 寬高為固定值時肯定是不行的;
當 android:layout_width(height)=”match_parent”或者“fill_parent”的時候,如果設置了weight屬性,那么根據它的weight值(可以理解為優先級)來占據空間,而且這個值是越小,占的空間越大,按且按且相反的大小比例分。
當 android:layout_width(height)=”wrap_parent”的時候,如果設置了weight屬性,那么weight值變大占據空間就變大,但是不是按照比例變化,而且weight值達到一定程度控件占據的控件大小就不會在變化。
谷歌工程師推薦大家使用android:layout_width(height)=”0dp”,因為如果你去嘗試看就會發現,只有寬或高設置成“0dp”時才是真正的按照“weight”的值按比例設置控件的大小。
關于weight
在相對布局中的控件是不能使用“weight”屬性的,但是,在RelativeLayout標簽中是可以有“weight”屬性的,也就是說你可以用”weight”屬性來控制這個相對布局在整個布局中的大小,卻不能用”weight”屬性來控制這個相對布局中控件的大小。
總結
以上是生活随笔為你收集整理的android 高度上分权重,安卓自适应布局(关于权重weight的使用技巧!)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: android判断参数非空,Androi
- 下一篇: android homme一般多钱,【A