layout_weight 的解释及使用

转自:http://my.oschina.net/jsan/blog/191492

在Android的控件布局中,有一个奇葩的 layout_weight 属性,定义如下:

layout_weight : 用于指定剩余空闲空间的分割比例。用法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<LinearLayout
  android:orientation="horizontal">
 
  <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_height"
      android:layout_weight="1"
      android:text="888"/>
 
  <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_height"
      android:layout_weight="1"
      android:text="999999"/>
 
</LinearLayout>

为什么说是奇葩呢?

以上面的布局代码为例,TextView-888 和 TextView-999999 是横向排列的2个控件,它们的layout_weight="1",说明这2个控件平分了所在LinearLayout的剩余的空闲空间, 我们很容易的就误认为这2个控件平分了水平方向的空间,即:各自占据了 50% 的宽度。

其实这是错误的,而是:TextView-999999控件所占据的宽度 > TextView-888所占据的宽度。因为999999字符占据的宽度大于888占据的宽度,即:w(999999) + 1/2空闲空间 > w(888) + 1/2空闲空间

这就是它奇葩的地方,很容易就让我们一直误认为是整个控件分割空间。到这里,大家一定会认为,这样的话,layout_weight 这个属性就没有什么意义了,原以为它可以分配空间呢,原来只是分割剩余空闲空间

其实,呵呵,layout_weight 是可以用来,这样比如2个控件的 layout_weight="1" 就可以各自50%平分整个空间了,因为:0 + 1/2空闲空间 = 0 + 1/2空闲空间

这是一个小技巧,也是非常实用的一个实用layout_weight分割方案:定义控件的 layout_width="0dp" 或 layout_height="0dp" 配上 layout_weight 就可以实现对整个空间的比例分割了。

下面定义了2个控件的 layout_width="0dp", layout_weight="1",实现了水平方向50%平均分割:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<LinearLayout
  android:orientation="horizontal">
 
  <TextView
      android:layout_width="0dp"
      android:layout_height="wrap_height"
      android:layout_weight="1"
      android:text="888"/>
 
  <TextView
      android:layout_width="0dp"
      android:layout_height="wrap_height"
      android:layout_weight="1"
      android:text="999999"/>
 
</LinearLayout>

下面定义了2个控件的 layout_height="0dp", layout_weight="1",实现了竖直方向50%平均分割:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<LinearLayout
  android:orientation="vertical">
 
  <TextView
      android:layout_width="wrap_content"
      android:layout_height="0dp"
      android:layout_weight="1"
      android:text="888"/>
 
  <TextView
      android:layout_width="wrap_content"
      android:layout_height="0dp"
      android:layout_weight="1"
      android:text="999999"/>
 
</LinearLayout>

 

使用Layout_weight时空间分配的计算方法:http://mobile.51cto.com/abased-375428.htm

最新文章

  1. Windows编程入门程序详解
  2. slideDoor(学习某编程网站的,仅作记录和学习)
  3. Android总结篇系列:Android广播机制
  4. POJ 1061青蛙的约会(拓展欧几里德算法)
  5. Hadoop集群中添加硬盘
  6. 从 SDWebImage 谈如何为开源软件做贡献
  7. css解决文字垂直居中
  8. ExtJS与后台Java交互
  9. .NET使用DAO.NET实体类模型操作数据库
  10. LVS-DR集群搭建
  11. python集合set相关操作
  12. @RequestParam加与不加的区别
  13. Dubbo--基于Zookeeper服务与Spring集成
  14. 11)django-ORM(操作增删改查)
  15. MySQL - 用户变量
  16. HTML 滚动条样式修改
  17. IP/子网掩码/网关/广播地址
  18. Centos 7 快速搭建IOS可用IPsec
  19. 管理 python logging 日志使用
  20. Python3 open()函数参数

热门文章

  1. TypeError: &#39;QueryDict&#39; object is not callable
  2. 变态最大值--nyoj题目811
  3. win7 PHP7.0的PDO扩展
  4. RESTful API实现
  5. MYSQL 关于索引的部分问题!
  6. SQL Server 823,824 错误
  7. 一步一步学python(四) - 字典
  8. 对话 UNIX: 关于 inode
  9. DotNet 资源大全(Awesome最新版)
  10. JavaScript 回车 焦点切换(摘抄)