深入理解Layout_weight

  估计很多人都对layout_weight这个属性感到疑惑。

  下面就通过几个例子来分析一下layout_weight这个属性。

  

<?xml version="1.0" encoding="utf-8"?>   
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
   
  <LinearLayout   
      android:orientation="horizontal"  
      android:layout_width="fill_parent"  
      android:layout_height="fill_parent"  
      android:layout_weight="1">   
      <TextView   
          android:text="red"  
          
          android:background="#aa0000"  
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"  
          android:layout_weight="1"/>   
      <TextView   
          android:text="green"  
        
          android:background="#00aa00"  
          android:layout_width="fill_parent" 
          android:layout_height="fill_parent"  
          android:layout_weight="2"/>   
      <TextView   
          android:text="blue"  
        
          android:background="#0000aa"  
          android:layout_width="fill_parent" 
          android:layout_height="fill_parent"  
          android:layout_weight="3"/>   
  
  </LinearLayout>   
</LinearLayout>  
  看了这个布局文件,估计大家会以为红:绿:蓝=3:2:1

但结果却是:


红:绿=2:1,而且没有蓝色。

到底是怎么一回事呢?

其实是这样子的:

首先看,3个TextView的排列方式:是水平排列的。

                因为是水平排列,所以看TextView的Layout_width.发现都是fill_parent。就是每一个TextView都是填充它的父控件。

                所以剩余空间为1-3=-2,然后再根据Layout_weight来分配剩余控件。

                所以红色分到的剩余空间为-2/6=-1/3 .加上它原本占的空间1,所有它占有的控件为父控件的2/3

                绿色分到的剩余空间为-2/6*2=-2/3.加上它原本占的空间1,所有它占有的控件为父控件的1/3

                而蓝色分到的剩余空间为-2/6*3=-1.加上它原本占的空间1,所有它占有的控件为父控件的0.

所以得知为什么  红:绿=2:1。


所以在使用layout_weight的属性时,不用死记书上写的属性值越小,占的比重越大。

而只需要知道,layout_weight是用来分配剩余空间的,然后每个分配到的剩余空间加上它本来占有的空间就是它实际占有的空间。

               


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值