首页 > 技术文章 > android:layout_weight越大所占比例越大和越大所占比例越小的两个例子

hamhog 2014-08-12 13:56 原文

摘要: 我的技术博客经常被流氓网站恶意爬取转载。请移步原文:http://www.cnblogs.com/hamhog/p/3907146.html,享受整齐的排版、有效的链接、正确的代码缩进、更好的阅读体验。

关于android:layout_weight到底是什么含义,在网上“越大所占比例越大”和“越大所占比例越小”两种说法都有。实际上这两种情况也都有。

例1:0dp

<LinearLayout android:orientation="vertical" 
        android:layout_width="match_parent" 
        android:layout_height="match_parent">
    <TextView  android:layout_width="fill_parent" android:layout_height="0dp" android:background="#ff0000" android:layout_weight="1" android:text="1"/>
    <TextView  android:layout_width="fill_parent" android:layout_height="0dp" android:background="#00ff00" android:layout_weight="2"  android:text="2"/>
</LinearLayout>

例2:

<LinearLayout android:orientation="vertical" 
        android:layout_width="match_parent" 
        android:layout_height="match_parent">
    <TextView  android:layout_width="fill_parent" android:layout_height="match_parent" android:background="#ff0000" android:layout_weight="1" android:text="1"/>
    <TextView  android:layout_width="fill_parent" android:layout_height="match_parent" android:background="#00ff00" android:layout_weight="2"  android:text="2"/>
</LinearLayout>

对两种情况的解释:

布局首先会给每个元素分配宽度,剩余的空间再分配给每个元素。

在分配剩余空间阶段,比例按照layout_weight,也就是越大分得越大。

在情况一里,固定宽度为0,只有第二阶段;情况二里,分配宽度能把所有空间分满,剩余的空间是负数,所以分配的越大,最终空间越小。

所以如果你要严格地让它按照某种比例,可以试试定为0dp。此时各个元素的比例即为weight。

推荐阅读