0%

Android开发 | LinearLayout布局

Android开发 | LinearLayout布局中的一些坑

Linear布局中的一些坑

  1. layout_weight分配的是 屏幕剩余的空间,如何理解?

    最普通情况下 在LinerLayout布局中 设置 orientationvertical, 布局中又包含了 三个块(我们以LinearLayout为例 填充一些背景颜色)

    代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent">

    <LinearLayout
    android:background="#00ff00"
    android:layout_width="100dp"
    android:layout_height="100dp"/>
    <LinearLayout
    android:background="#ffff00"
    android:layout_width="100dp"
    android:layout_height="100dp"/>
    <LinearLayout
    android:background="#00ffff"
    android:layout_width="100dp"
    android:layout_height="100dp"/>

    </LinearLayout>

    结果如图:

    image-20210319095755151

    但 当我们设置每个块的android:layout_weight="1",并且 android:layout_height="0dp"时 效果如下:,三个块在纵向平分了整个屏幕

    image-20210319100148655

    设置每个块的android:layout_weight="1",并且 最后一个块android:layout_height="100dp"时 效果如下:三个块就不是平分 屏幕里 而是下面这个要大

    image-20210319100408834

    当设置第一个块的 android:layout_height="match_parent",其余块的layout_height="0dp",其余块的weight 均为1,结果并没有将屏幕三等分,而是只有最上面的块 ,因为layout_weight 分配的是 屏幕剩余空间

    代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent">

    <LinearLayout
    android:background="#00ff00"
    android:layout_width="100dp"
    android:layout_weight="1"
    android:layout_height="match_parent"/>
    <LinearLayout
    android:background="#ffff00"
    android:layout_width="100dp"
    android:layout_weight="1"
    android:layout_height="0dp"/>
    <LinearLayout
    android:background="#00ffff"
    android:layout_width="100dp"
    android:layout_weight="1"
    android:layout_height="0dp"/>

    </LinearLayout>
    image-20210319100910853