标签:
首先来查看android sdk文档,有这么一段话
LinearLayout
also supports assigning a weight to individual children with the android:layout_weight
attribute. This attribute assigns an "importance" value to a view in terms of how much space is should occupy on the screen. A larger weight value allows it to expand to fill any remaining space in the parent view. Child views can specify a weight value, and then any remaining space in the view group is assigned to children in the proportion of their declared weight. Default weight is zero.
我们从文档中可以看出LinearLayout中子控件可以使用layout_weight 属性来分配所占的“权重”,但是实际使用的过程中,经常会出错,会让人感到疑惑,下面是自己总结的一些经验:
以水平(垂直方向类似)LinearLayout为例:
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="16dp" android:layout_marginRight="16dp" > <Button android:id="@+id/crime_date" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" /> <CheckBox android:id="@+id/crime_solved" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="@string/crime_solved_label" /> </LinearLayout>
LinearLayout是个水平线性布局,会根据每个子成员layout_width和layout_weight来决定应该给他们分配多少空间, 遵循以下规则:
来再看一个经常让人误解的例子:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_height="wrap_content" android:text="small" android:textColor="#02F" android:layout_width="wrap_content" android:layout_weight="1" /> <TextView android:layout_height="wrap_content" android:textColor="#F20" android:text="A very very long text that needs to wrap.A very very long" android:layout_width="wrap_content" android:layout_weight="1" /> </LinearLayout>
它的效果是这样:
它并没有按照weight去1:1的分配空间比例,这是因为布局管理器按照第一条规则满足了layout_width=’wrap_content’,这种情况下,如果确实想按照1:1的空间来分配,就只能设置layout_width=’0dp”, 这样做的效果就是这样:
欢迎斧正
Android UI: LinearLayout中layout_weight 属性的使用规则
标签:
原文地址:http://www.cnblogs.com/jimmytech/p/4557396.html