Android Weight 使用 详解

Android开发屏幕适配离不开 Weight 这一属性,该属性只适用于Linearlayout 中,常见的使用方式:

 1. <? 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:orientation= "horizental"

    android:background= "@color/white"

    >

     <Button

          android:width="0dp"

          android:height="wrap_content"

          android:weight="1.0"

          android:text="button1"

     />

     <Button

          android:width="0dp"

          android:height="wrap_content"

          android:weight="2.0"

          android:text="button1"

     />

</LinearLayout>



以上定义的形式为 设定 需要按比例分配的 宽或高为 0dp 然后在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:orientation= "horizental"

    android:background= "@color/white"

    >

     <Button

          android:width="match_parent"

          android:height="wrap_content"

          android:weight="1.0"

          android:text="button1"

     />

     <Button

          android:width="match_parent"

          android:height="wrap_content"

          android:weight="2.0"

          android:text="button1"

     />

</LinearLayout>

以上定义的形式为 设定 需要按比例分配的 宽或高为match_parent 然后在weight 中设定所占的空间大小比例

  最终显示的样式,正如我们设计的比例相反。


这是为什么呢?

 现在 规定一下 整个UI 布局的宽度 为 x,暂将以上两种方式 称呼为:方式1,方式2;

  范式: 

   计算出的宽度=原有宽度+剩余空间其所占的百分比宽度


方式1:

   因为其展示,正如我们的比例设定的是一样的,所以计算出 的宽度为 1/3 x

   原有宽度定义为0dp,

 因为btn1 和btn2 的width 均为0dp,所以 剩余空间的宽度为 x

  btn1:  1/3x = 0+ x*1/3

  btn2:  2/3x = 0+x*2/3


方式2:

  因为 其 width 为match_parent ,所以其原有宽度为 x;

  因为 放置了两个btn ,他们的宽度均为match_parent,所以两个按钮的总宽度为 2x,所以剩余空间 的宽度为 x-2x;

 btn1: 2/3x = x+(x-2x)*1/3

 btn2: 1/3x = x+(x-2x)*2/3

感谢慕课网的大神,学习到很多



转载于:https://my.oschina.net/leov1/blog/501986

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值