LinearLayout布局的Layout_weight

只有在Linearlayout中,Layout_weight属性才有效。

之所以android:layout_weight会引起争议,是因为在设置该属性的同时,设置android:layout_width为wrap_content和match_parent会造成两种截然相反的效果。

一 · warp_content

先看一下布局

<?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="horizontal">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        android:layout_weight="1"
        android:background="@color/red"
        android:text="1"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        android:layout_weight="2"
        android:background="@color/green"
        android:text="2" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        android:layout_weight="3"
        android:background="@color/blue"
        android:text="3" />
</LinearLayout>

效果图:

这里写图片描述

二 · match_parent(或 fill_parent)

布局

<?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="horizontal">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        android:layout_weight="1"
        android:background="@color/red"
        android:text="1"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        android:layout_weight="2"
        android:background="@color/green"
        android:text="2" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        android:layout_weight="3"
        android:background="@color/blue"
        android:text="3" />
</LinearLayout>

效果图

这里写图片描述

总结 :

View的height默认为0。所以,一旦View设置weight,这个View的在绘制的时候执行了两次onMeasure方法。

layout_weight的真实含义是:一旦View设置了该属性,那么该 View的宽度等于原有宽度(android:layout_width)加上剩余空间的占比!

设屏幕宽度为L:

  • 在两个view的宽度都为match_parent的情况下,原有宽度为L,三个的View的宽度都为L,那么剩余宽度为L-(L+L+L) = -2L, 左边的View占比六分之一,所以总宽度是L+(-2L)*1/6 = (4/6)L,中间的View占比六分之二,所以总宽度是L+(-2L)*2/6 = (2/6)L,所以前两个View已经占满了屏幕,第三个已经看不见了。

  • 在两个view的宽度都为warp_content的情况下,可以将weight理解为占空比,即左边的占比1 / 6,中间占比 2 / 6,右边占比 3 / 6。

Google官方推荐,当使用weight属性时,将width设为0dip即可,效果跟设成wrap_content是一样的。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值