Android 权重正确解释以及解释误区分析

1.首先声明只有在Linearlayout中,layout_weight属性才有效。

在这里我们设置三个的权重比为 蓝1:黄2:红2那么它的效果是不是 蓝1:黄2:红2呢

 <TextView
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
       android:background="@color/blue"
        />
    <TextView
        android:layout_weight="2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/yellow"
        />
    <TextView
        android:layout_weight="2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/red"
        />

然而实际的效果并不是蓝1:黄2:红2而是蓝2:黄1:红1大家是不是感觉这个安卓的权重是成反比呢这个效果的理解就是这样,但是事实并不是这样的

实际上它是用来指定(剩余空闲空间)的分割比例,而非按比例分配整个空间。另外android:layout_weight会引起争议,是因为在设置该属性的同时, 设置android:layout_width为wrap_content和match_parent会造成两种截然相反的效果。因为在这里设置为match_parent是用了屏幕的宽度(假设屏幕的宽度为1080),所以三个颜色设置下来屏幕的闲散空间为-2160那么按照刚才的笔记1080+(-2160*1/5)是不是就是最多的那份所以会造成一种反比的效果。

如果想用layout_weight平均分配空间,正确方式是将layout_width(或layout_height)设置为0dp或者设置为wrap_content,
      再通过layout_weight按比例分配空间

 关键点在于搞清楚什么是剩余空闲空间

猜你喜欢

转载自blog.csdn.net/yjt520557/article/details/83097431
今日推荐