首先声明只有在Linearlayout中,该属性才有效。之所以android:layout_weight会引起争议,是因为在设置该属性的同时,设置android:layout_width为wrap_content和match_parent会造成两种截然相反的效果。如下所示:

[html] view plain copy print ?
  1. <LinearLayout
  2. android:layout_width="match_parent"
  3. android:layout_height="wrap_content"
  4. android:orientation="horizontal">
  5. <TextView
  6. android:layout_width="match_parent"
  7. android:layout_height="wrap_content"
  8. android:layout_weight="1"
  9. android:background="@android:color/black"
  10. android:text="111"
  11. android:textSize="20sp"/>
  12. <TextView
  13. android:layout_width="match_parent"
  14. android:layout_height="wrap_content"
  15. android:layout_weight="2"
  16. android:background="@android:color/holo_green_light"
  17. android:text="222"
  18. android:textSize="20sp"/>

上面的布局将两个TextView的宽度均设为match_parent,一个权重为1,一个权重为2.得到效果如下:


可以看到权重为1的反而占了三分之二!

再看如下布局:

[html] view plain copy print ?
  1. <LinearLayout
  2. android:layout_width="match_parent"
  3. android:layout_height="wrap_content"
  4. android:orientation="horizontal">
  5. <TextView
  6. android:layout_width="wrap_content"
  7. android:layout_height="wrap_content"
  8. android:layout_weight="1"
  9. android:background="@android:color/black"
  10. android:text="111"
  11. android:textSize="20sp"/>
  12. <TextView
  13. android:layout_width="wrap_content"
  14. android:layout_height="wrap_content"
  15. android:layout_weight="2"
  16. android:background="@android:color/holo_green_light"
  17. android:text="222"
  18. android:textSize="20sp"/>
  19. </LinearLayout>

即宽度为wrap_content,得到视图如下:


左边 TextView占比三分之一,又正常了。

android:layout_weight的真实含义是:一旦View设置了该属性(假设有效的情况下),那么该 View的宽度等于原有宽度(android:layout_width)加上剩余空间的占比!

设屏幕宽度为L,在两个view的宽度都为match_parent的情况下,原有宽度为L,两个的View的宽度都为L,那么剩余宽度为L-(L+L) = -L, 左边的View占比三分之一,所以总宽度是L+(-L)*1/3 = (2/3)L.事实上默认的View的weight这个值为0,一旦设置了这个值,那么所在view在绘制的时候执行onMeasure两次的原因就在这。

Google官方推荐,当使用weight属性时,将width设为0dip即可,效果跟设成wrap_content是一样的。这样weight就可以理解为占比了!



原文地址:http://blog.csdn.net/yanzi1225627/article/details/24667299

更多相关文章

  1. mtk android 配置mcp
  2. Android(安卓)Dialog自定义宽高
  3. Android酷炫实用的开源框架(UI框架)
  4. android sdcard文件存储 + 媒体库更新方法
  5. Android改变系统自带ProgressDialog的文字大小
  6. Android(安卓)完全掌握Service
  7. Android大图片加载处理
  8. Android改变系统自带ProgressDialog的文字大小
  9. android 获取实际view 宽度高度

随机推荐

  1. 深入解析Android的自定义布局
  2. android Application Component研究之Bro
  3. Android(安卓)Canvas绘图描述Android(安
  4. Android周学习Step By Step(6)--Android的
  5. android:configChanges属性
  6. Android(安卓)TextView属性
  7. FrameLayout使用
  8. Android(安卓)FrameWork——Touch事件派
  9. Android读写XML(下)——创建XML文档
  10. zz :Android测试之Monkey