Linear Layout and weight in Android

I always read about this funny weight value in the Android documentations. Now I want to try it for the first time but it isn't working at all.

As I understand it from the documentations this layout:

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

     <Button
        android:text="Register"
        android:id="@+id/register"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dip"
        weight="1" />

     <Button
        android:text="Not this time"
        android:id="@+id/cancel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dip"
        weight="1" />

  </LinearLayout>

should create two buttons that are horizontally aligned and share the space equally. The problem is the two buttons don't grow to fill the space.

I would like the buttons to grow and fill the whole line. If both buttons are set to match parent only the first button is shown and fills the whole line.


You are not setting the layout_weight property. Your code reads weight="1" and it should read android:layout_weight="1" .


3 things to remember:

  • set the android:layout_width of the children to "0dp"
  • set the android:weightSum of the parent (edit: as Jason Moore noticed, this attribute is optional, because by default it is set to the children's layout_weight sum)
  • set the android:layout_weight of each child proportionally (eg weightSum="5", three children: layout_weight="1", layout_weight="3", layout_weight="1")
  • Example:

        <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:weightSum="5">
    
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="1" />
    
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="3"
            android:text="2" />
    
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="3" />
    
        </LinearLayout>
    

    And the result:


    It's android:layout_weight . Weight can only be used in LinearLayout . If the orientation of linearlayout is Vertical, then use android:layout_height="0dp" and if the orientation is horizontal, then use android:layout_width = "0dp" . It'll work perfectly.

    链接地址: http://www.djcxy.com/p/93256.html

    上一篇: LinearLayout权重在Listview中不起作用

    下一篇: Android中的线性布局和重量