关于android:layout_weight属性你不知道的事

刚开始做安卓开发时,使用xml写布局时就使用过android:layout_weight属性吧。
首先该属性一定要是在Linearlayout布局中才会有效果。
这属性就是权重的意思:该 View的宽度或者高度等于原有宽度或者高度(android:layout_width)加上剩余空间的占比!(这里千万注意剩余空间)

直接上代码:

<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="com.dgg1.weight.MainActivity">

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="#ff00ff"
        android:text="按钮1" />

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:background="#ffff00"
        android:text="按钮2" />
</LinearLayout>

实现的效果:
这里写图片描述

这也是官方的写法。

下面我换一种写法:

<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="com.dgg1.weight.MainActivity">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="#ff00ff"
        android:text="按钮1" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:background="#ffff00"
        android:text="按钮2" />
</LinearLayout>

诶,这不是一模一样么(嘿嘿,不仔细看的人可能还真的觉得没改哪里)我这里把layout_width从0改成了match_parent。
实现的效果:
这里写图片描述

你会发现效果和之前的效果恰恰相反,为什么会出现这个效果呢?layout_weight属性的意思为控件原本的宽度+剩余空间的比例宽度!
第一种情况:假设这个屏幕的宽度为100,当你把宽度设置为0dp时,那button2的宽度就为0(控件的宽度)+100(剩余的宽度)*2/3 (比例)= 67(实际宽度),button1的宽度就为0+100*1/3 = 33;

第二种情况:假设这个屏幕的宽度为100,当你把宽度设置为match_parent时,那button1的宽度就为100,button2的宽度也为100,那么剩余宽度为100-(100+100)=-100(剩余宽度就为-100了),那么继续换算button1的实际宽度为100+(-100)*1/3 = 67,button2的实际宽度为100+(-100)*2/3 = 33了。
所以就会出现恰恰相反的结果了。(官方推荐使用第一种写法)

但是有时候使用到 include标签的复用布局时可能需要使用到第二种写法。

(如有问题或遗漏欢迎留言探讨,共同进步)

猜你喜欢

转载自blog.csdn.net/qq77485042/article/details/77446571