Android布局Layout_weight详细剖析

410 查看

引言

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

官方文档描述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.

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.

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

原理

其实文档里面已经说的很清楚了,layout_weight这个属性是用来给剩余空间分配的,所以我们只需要计算剩余空间的分配就行了,它其实是先根据你的layout_width或者layout_height计算好预先的值,然后整个屏幕减去所有控件的值,计算的结果可能是负数,但是没有关系,负数一样可以根据比例分配,然后加总在原先的值上,这样就成了我们看到的画面。