Android開發(二十九)——layout_weight的含義

首先聲明只有在Linearlayout中,該屬性纔有效。之因此android:layout_weight會引發爭議,是由於在設置該屬性的同時,設置android:layout_width爲wrap_content和match_parent會形成兩種截然相反的效果。以下所示:android

 <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@android:color/black"
            android:text="111"
            android:textSize="20sp" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:background="@android:color/holo_green_light"
            android:text="222"
            android:textSize="20sp" />

上面的佈局將兩個TextView的寬度均設爲match_parent,一個權重爲1,一個權重爲2.獲得效果以下:佈局

能夠看到權重爲1的反而佔了三分之二!spa

再看以下佈局:.net

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="@android:color/black"
        android:text="111"
        android:textSize="20sp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:background="@android:color/holo_green_light"
        android:text="222"
        android:textSize="20sp" />
</LinearLayout>

即寬度爲wrap_content,獲得視圖以下:code

左邊 TextView佔比三分之一,又正常了。blog

 

android:layout_weight的真實含義是:一旦View設置了該屬性(假設有效的狀況下),那麼該 View的寬度等於原有寬度(android:layout_width)加上剩餘空間的佔比!ip

設屏幕寬度爲L,在兩個view的寬度都爲match_parent的狀況下,原有寬度爲L,兩個的View的寬度都爲L,那麼剩餘寬度爲L-(L+L) = -L, 左邊的View佔比三分之一,因此總寬度是L+(-L)*1/3 = (2/3)L.事實上默認的View的weight這個值爲0,一旦設置了這個值,那麼所在view在繪製的時候執行onMeasure兩次的緣由就在這。io

Google官方推薦,當使用weight屬性時,將width設爲0dip便可,效果跟設成wrap_content是同樣的。這樣weight就能夠理解爲佔比了!class

 

參考:im

[1] android:layout_weight的真實含義.http://blog.csdn.net/yanzi1225627/article/details/24667299

相關文章
相關標籤/搜索