LinearLayout(线性布局)关于fill_parent和weight搭配使用计算的详细理解

基于: https://www.runoob.com/w3cnote/android-tutorial-linearlayout.html

说明:代码都是基于原文章,本文只对其中计算方面的理解稍加分析以便于理解!!!

写这段简单的代码:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    
    xmlns:tools="http://schemas.android.com/tools"    
    android:id="@+id/LinearLayout1"    
    android:layout_width="match_parent"    
    android:layout_height="match_parent" >    
    
    <TextView    
        android:layout_weight="1"    
        android:layout_width="fill_parent"    
        android:layout_height="fill_parent"    
        android:text="one"     
        android:background="#98FB98"    
     />    
     <TextView    
        android:layout_weight="2"    
        android:layout_width="fill_parent"    
        android:layout_height="fill_parent"    
        android:text="two"     
        android:background="#FFFF00"    
     />    
     <TextView    
        android:layout_weight="3"    
        android:layout_width="fill_parent"    
        android:layout_height="fill_parent"    
        android:text="three"     
        android:background="#FF00FF"    
     />    
    
</LinearLayout> 

 

效果图:

原作者分析:这个时候就会有疑问了,怎么会这样,这比例是2:1吧,那么three去哪了?代码里面明明有 three的啊,还设置了3的,而1和2的比例也不对耶,1:2:3却变成了2:1:0,怎么会这样呢? 答:这里其实没那么简单的,还是需要我们计算的,网上给出的算法有几种,这里就给出笔者 觉得比较容易理解的一种: step 1:个个都是fill_parent,但是屏幕只有一个啦,那么1 - 3 = - 2 fill_parent step 2:依次比例是1/6,2/6,3/6 step 3:先到先得,先分给one,计算: 1 - 2 * (1/6) = 2/3 fill_parent 接着到two,计算: 1 - 2 * (2/6) = 1/3 fill_parent 最后到three,计算 1 - 2 * (3/6) = 0 fill_parent step 4:所以最后的结果是:one占了两份,two占了一份,three什么都木有 以上就是为什么three没有出现的原因了,或许大家看完还是有点蒙,没事,我们举多几个例子试试就知道了!

step 1:个个都是fill_parent,但是屏幕只有一个啦,所以只有1个fill_parent, 3个控件要3个fill_parent, 所以1-3=-2fill_parent,这里还差两个fill_parent, 差两个怎么办呢?fill_parent说了,为了保证先到先得(早起的鸟儿有虫吃)的原则,这个缺少的面积要大家共同来分担;

step 2:根据权重weight, 大家每个占的比例是1:2:3,所以承担的损失就得按比例来分,各承担6份中得1/2/3;所以依次比例是1/6,2/6,3/6 ;

step 3:先到先得,先分给one, 一个fill_parent, one说我只预定了1份,所以我承担-2fill_parent的1/6损失- 2 * (1/6)就好了,所以计算: 1 - 2 * (1/6) = 2/3 fill_parent;

              接着到two,计算: 1 - 2 * (2/6) = 1/3 fill_parent

              最后到three,计算 1 - 2 * (3/6) = 0 fill_parent 

step 4:所以最后的结果是:one占了两份,two占了一份,three什么都木有(太贪心了, 哈哈哈。。。)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值