线性布局中weight权重异常问题分析。

大家可能遇到这样的问题:
当给组件的大小,设置match_parent时,然后将组件的权重设置为1 2 3时,会发现只显示两个组件,并且比例为2:1。
针对这个问题,进行说明。
问题代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"


    tools:context=".MainActivity">

    <Button
        android:id="@+id/button5"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:text="Button" />

    <Button
        android:id="@+id/button6"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="2"
        android:text="Button" />
    <Button
        android:id="@+id/button7"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="3"
        android:text="Button" />

   
</LinearLayout>

效果图:
在这里插入图片描述
结果分析:
step1: 这里将match_parent简称MP,为一个单位,代表的含义是,该布局的全填充大小。
step2:1 - 3 =-2 MP, 意思是,有三个MP ,但父布局只有一个MP,故多出来了两个MP。
step3:下来对多出来的两个MP进行分配: -2 ×1/6 =-1/3
step4:故button1有:1+(-1/3)个MP 既 2/3个MP
继续运算可得 2:1:0。

发布了9 篇原创文章 · 获赞 13 · 访问量 2874

猜你喜欢

转载自blog.csdn.net/weixin_44696542/article/details/104500502