android: android 布局中的weight 属性

android: weight是线性布局的特有属性,控件的宽度和高度的不同,也会存在差异。

示例1:将宽度设置为包裹类型wrap_content或0dp

<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context=".WeightApiUseDemoActivity"
    android:orientation="horizontal"
    >

    <Button
        android:layout_width="0dip"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Button 1"
        />

    <Button
        android:layout_width="0dip"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:text="Button 2"
        />

</LinearLayout>

运行:

示例2: 将宽度设置为match_parent时

<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context=".WeightApiUseDemoActivity"
    android:orientation="horizontal"
    >

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

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

</LinearLayout>

运行:

小结: 第一种现象很好理解,当放置两个宽度为0dip或是wrap_content的按钮时,由于宽度并未确定,那Button1所占的宽度就是 1 / (1+2) = 1/ 3, 也就是总长度的1/3;Button2 所占的宽度是 2 / (1+2) = 2 / 3, 也就是总长度的2/3。

第二种现象就很奇怪了,其实这是因为View在绘制的时候有一个规则,如果给View添加了android:weight属性,那么这个View的最终宽度 = View本来定义的宽度 +   View在LinearLayout中剩余空间中所占比例的宽度。什么意思呢,假设线性布局的总宽度为 L ,

拿第一种现象来说

Button1的宽度 = 0dip + ( L - Button1的宽度(也就是0dip) - Button2的宽度(也是0dip) ) * 1/3 = 0dip + L * 1/3 = 1/3 L。
Button2的宽度 =  0dip + ( L - Button1的宽度(也就是0dip) - Button2的宽度(也是0dip) ) * 2/3 = 0dip + L * 2/3 = 2/3 L。

拿第二种现象来说

Button1的宽度 = L + ( L - Button1的宽度(也就是L) - Button2的宽度(也是L) ) * 1/3 = L + (-L) * 1/3 = L - 1/3 L = 2/ 3L。
Button2的宽度 = L + ( L - Button1的宽度(也就是L) - Button2的宽度(也是L) ) * 2/3 = L + (-L) * 2/3 = L - 2/3 L = 1/ 3L。

原文地址:https://www.cnblogs.com/yongdaimi/p/11821616.html