首先声明只有在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