关于Layout Weight一些使用技巧

LinearLayout中通过layout weight属性来表示这个孩子视图view在整个手机屏幕占的大小比例。

一般不在孩子视图里面写这个属性的时候,则默认为0

android:layout_weight="0"

For example, if there are three text fields and two of them declare a weight of 1, while the other is given no weight, the third text field without weight will not grow and will only occupy the area required by its content. The other two will expand equally to fill the space remaining after all three fields are measured. If the third field is then given a weight of 2 (instead of 0), then it is now declared more important than both the others, so it gets half the total remaining space, while the first two share the rest equally.


比如,如果一个LinearLayout有3个text的孩子视图,其中2个声明layout_weight=1;另外一个没有声明,即默认为0,占用的空间大小应该和它的内容一样。那么这2个声明了为1的,就平分剩下的空间。

如果第3个声明不是默认为0而是1的话,那么第3个声明占用了全部空间的一半,另外2个声明了1的平分另外的一半.

看下面一个例子:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:orientation="vertical" >
    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="@string/to" />
    <EditText
        android:layout_width="fill_parent"
          android:layout_height="0dp"
        android:layout_weight="1"
        android:hint="@string/subject" />
    <EditText
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:gravity="top"
        android:hint="@string/message" />
    <Button
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_gravity="top"
        android:text="@string/send" />
</LinearLayout>


上面运行的结果如下:

关于Layout Weight一些使用技巧

明显to和send所在的区域,因为默认layout_weight不显示;所以大小默认为0,占用的空间为内容大小。

其他的2个edit平均占用剩下的空间。

关于

 android:layout_height="0dp"
 android:layout_weight="1"

为什么药这样设置,可以看文档上面的这段话:



Equally weighted children

To create a linear layout in which each child uses the same amount of space on the screen, set theandroid:layout_height of each view to "0dp" (for a vertical layout) or theandroid:layout_width of each view to "0dp" (for a horizontal layout). Then set the android:layout_weight of each view to "1".



你可能感兴趣的:(关于Layout Weight一些使用技巧)