Android布局Layout_weight详细剖析

引言

最近在看Android开发,对于不少书上关于layout_weight的讲解感受很是费解,不少都是像公式同样要求记住,而并未说明缘由,笔者查询了android的官方开发文档,Trainning里面有一段关于layout_weight属性很是形象的描述,然后在网上看到了一篇关于这个属性的讲解,很是精彩,特此在这里摘录。html

官方文档描述layout_weight

The weight value is a number that specifies the amount of remaining space each view should consume, relative to the amount consumed by sibling views. This works kind of like the amount of ingredients in a drink recipe: "2 parts soda, 1 part syrup" means two-thirds of the drink is soda. For example, if you give one view a weight of 2 and another one a weight of 1, the sum is 3, so the first view fills 2/3 of the remaining space and the second view fills the rest. If you add a third view and give it a weight of 1, then the first view (with weight of 2) now gets 1/2 the remaining space, while the remaining two each get 1/4.android

The default weight for all views is 0, so if you specify any weight value greater than 0 to only one view, then that view fills whatever space remains after all views are given the space they require.ui

这是什么意思呢,文档里面说layout_weight是用来指定视图应当占据的剩余空间,这个剩余空间是根据权重值来分配的,也就是说,若是一个视图分配权重2,一个是1,那么,第一个视图将会占据三分之二的空间,第二个视图将会占据三分之一的空间,默认的值是0.
可是这是在wrap_content的状况下,才会发生,一旦将属性指定为match_parent,那么空间的配比就会根据权重值的反比,也就是说刚才的状况下第一个视图将会占据三分之一,而第二个视图将会占据三分之二。
这个特性让人很是费解,并且不少书上都只是像背口诀同样记住,然后笔者在网上发现了一篇文章,文章地址,里面讲述的就很清晰。spa

原理

其实文档里面已经说的很清楚了,layout_weight这个属性是用来给剩余空间分配的,因此咱们只须要计算剩余空间的分配就好了,它实际上是先根据你的layout_width或者layout_height计算好预先的值,而后整个屏幕减去全部控件的值,计算的结果多是负数,可是没有关系,负数同样能够根据比例分配,而后加总在原先的值上,这样就成了咱们看到的画面。rest

相关文章
相关标签/搜索