关于weight属性使用的一些细节

之前被这个属性困扰过好久,今天一个偶然的机会,终于把这个搞清楚了,现在与大家分享一下。

假设我们要在一个LinearLayout布局中显示两个按钮,button1和button2,button2的宽度是button1的二倍,正常情况下使用weight应该是这样的:

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

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

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

</LinearLayout>

注意两个button的宽都是0dp

效果图:
这里写图片描述

可是如果换一种方式:

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

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

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

</LinearLayout>

两个button的宽度都是match_parent,情况立马发生转变:
这里写图片描述

我以前就在这里不知道纠结了多少回,那么我们到底该怎么理解weight这个属性呢?

设置了weight属性的View的宽度等于原有宽度加上剩余空间的占比,其中剩余空间是指屏幕宽度相对于控件总宽度剩余的空间大小。

以第一种情况为例


假设屏幕宽度为L,第一个button原有宽度是0dp,那么该button的宽度为0+(L-0)×1/3 = (1/3)L
其中(L-0)中,L表示屏幕宽度,0表示两个控件的总宽度


以第二种情况为例


假设屏幕宽度为L,因为两个都是match_parent,所以总宽度是2L,那么对于第一个button而言,它的宽度为:L+(L-2L)×1/3 = (2/3)L
其中(L-2L)中,L表示屏幕宽度,2L表示两个控件的总宽度


总结:建议大家在使用weight属性的过程中把相应的宽或者高设置为0dp,这也是Google推荐的做法。水平排列的话宽设置为0dp,竖直排列的话高设置为0dp.

版权声明:本文为博主原创文章,未经博主允许不得转载。若有错误地方,还望批评指正,不胜感激。

posted @ 2015-08-29 18:17  江南一点雨  阅读(980)  评论(0编辑  收藏  举报