layout_weight屬性的那些坑

以前在寫android程序的時候,就在layout_weight屬性這部分吃過虧

首先看一下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="vertical" >
    <EditText 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Text1"/>
    <EditText 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:text="Text2"/>

</LinearLayout>

顯示結果:


很明顯最後結果是上面的Text1和下面的Text2以1:2的比例瓜分手機屏幕

但是當我們把Text1和Text2的layout_height設成fill_parent 或者match_parent的話

<?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="vertical" >
    <EditText 
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:text="Text1"/>
    <EditText 
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:layout_weight="2"
        android:text="Text2"/>

</LinearLayout>

顯示結果爲:


有意思的現象出現了,此時的Text1和Text2是以2:1的比例分佈的

很奇怪的現象,其實layout_weight的意思是對剩餘的空間進行瓜分

也就是說,這裏的兩個Text,都是1 * parentHeight

剩餘空間就是1 * parentHeight - 2 * parentHeight = -1 * parentHeight

此時的Text1就會變成:1 * parentHeight + (-1 * parentHeight * 1/3) = 2/3 * parentHeight

同理此時的Text2就會變成:1 * parentHeight + (-1 * parentHeight * 2/3) = 1/3 * parentHeight

所以就會得出Text1:Text2的比值爲2 : 1,跟我們想象的1:2正好相反


因此,在我們用layout_weight屬性的時候,

如果控件的父控件是水平方向,不要設置layout_width爲fill_parent或者match_parent,

官方推薦設置控件的layout_width="0dp"(用wrap_content也是可以的)

如果控件的父控件是垂直方向,不要設置layout_height爲fill_parent或者match_parent,

官方推薦設置控件的layout_height="0dp"(用wrap_content也是可以的)


那麼當設置了layout_weight的控件遇到沒設置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="vertical" >
    <EditText 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Text1"/>
    <EditText 
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:text="Text2"/>
    <EditText 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Text3"/>

</LinearLayout>

顯示結果:


如圖所見,設置有layout_weight屬性的控件會按照比例分割剩餘空間

如果只有一個設置layout_weight屬性的控件,那麼它將獨佔剩餘空間



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章