Android中LinearLayout布局中layout_weight属性的作用

1、 首先声明只有在Linearlayout布局中,layout_weight属性才有效。

2、它是用来指定(剩余空闲空间)的分割比例,而非按比例分配整个空间。为什么这样说呢?看如下代码:

<?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">

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

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

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="按钮3"
        android:layout_weight="1"/>
</LinearLayout>

效果图为:

可以看到三个按钮的android:layout_weight分别是2:1:1,那它们的宽度应该也是2:1:1,但按钮1却根本没有显示出来,所以android:layout_weight是按比例划分activity的宽度这一理解是错误的,正确的理解是android:layout_weight是按比例划分activity的剩余空间的。打个比方,activity的宽度是1080,因为三个按钮的android:layout_width都是等于"match_parent",所以三个按钮的宽度都是1080,而activity的宽度只有1080,所以activity的剩余空间为1080-1080-1080-1080=-2160,三个按钮按比例划分剩余空间,所以按钮1的宽度为1080+(-2160*2/4)=0,按钮2和按钮3的宽度都是1080+(-2160*1/2)=540,所以效果图是按钮2和按钮3宽度一样,各占activity宽度的一半。

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

4、如果想用layout_weight平均分配空间,正确方式是将layout_width(或layout_height)设置为0dp,再通过layout_weight按比例分配空间即可。

<?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">

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

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

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="按钮3"
        android:layout_weight="1"/>
</LinearLayout>

效果图:

猜你喜欢

转载自blog.csdn.net/weixin_42687829/article/details/82777596