神奇的layout_weight属性

1、概述

        在线性布局有时候为了控制一下屏幕的适配,可以使用layout_weight这个属性来设置权重,要注意一点,这个属性只有在Linearlayout中才有效,这个属性往往会随着android:layout_width设置而变化,有时候可能出现一些意想不到的效果,下面来看看

2、实例效果

布局文件如下,水平放了2个文本,设置不同权重1:2

2.1、layout_width=“0dp”

<span style="font-size:18px;"><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="aaa"
        android:background="@android:color/holo_blue_bright"
        android:textSize="20sp" />
    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:background="@android:color/holo_green_dark"
        android:text="bbb"
        android:textSize="20sp" />


</LinearLayout></span>

正常1:2权重显示布局



2.2、layout_width=“match_parent”

width改成match_parent

惊奇的发现,说好的1:2咋变成2:1了呢,

咋回事呢?下面会详细解释

2.3、layout_width=“wrap_content”

此时又恢复正常


3、解开谜底

【原则】Linearlayout中的layout_weight属性首先按照控件声明的尺寸进行分配,然后将剩下的尺寸按照weight分配

这里看出layout_width=“0dp”和layout_width=“wrap_content”是一样的,他们是把宽度交给实际控件的宽度起始都为0;

而layout_width=“match_parent”是将控件在一开始就设置成了父控件Linearlayout的大小假设为S,,俩个控件都是match_parent,则对应每个TextView控件一开始大小就为S

那个剩下的尺寸为:原屏幕尺寸减去控件占有尺寸,即S-(S+S)= -S ;此时第一个TextVIew占1/3权重,则实际宽度为S+(-S)*1/3 = S* 2/3,同理可知第二个TextView占S*1/3。

这下谜底解开了吧。Google在官方推荐,当使用layout_weight属性时,将width设为0dip即可,效果跟设成wrap_content是一样的。


4、其他

单一控件实现权重布局

如果我们只有一个TextView要想实现这一个控件占1/2权重怎么办?此时没有其他控件跟我们均分,此时可以在Linearlayout中将android:weightSum="2",然后在texiview中权重设置为1即可

布局文件为

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:weightSum="2"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="@android:color/holo_blue_bright"
        android:text="aaa"
        android:textSize="20sp" />


</LinearLayout>

效果图为


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值