打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
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 累加得到。

例子:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="horizontal"
    android:weightSum="1">

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="0.5"
        android:text="@string/hello_world" />

</LinearLayout>

内部的计算原理是:

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”属性来控制这个相对布局中控件的大小。

参考博客:
http://www.open-open.com/lib/view/open1473737843624.html
http://essay.tmooc.cn/forum.php?mod=viewthread&tid=583

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
LinearLayout(线性布局)
android:layout_weight属性详解
New UI
Android:Layout_weight的深刻理解
android相对布局
Android日常布局适用范围介绍和关键属性说明
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服