android: weight是线性布局的特有属性,控件的宽度和高度的不同,也会存在差异。

示例1:将宽度设置为包裹类型wrap_content或0dp

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".WeightApiUseDemoActivity"
android:orientation="horizontal"
> <Button
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button 1"
/> <Button
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="Button 2"
/> </LinearLayout>

运行:

示例2: 将宽度设置为match_parent时

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".WeightApiUseDemoActivity"
android:orientation="horizontal"
> <Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button 1"
/> <Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="Button 2"
/> </LinearLayout>

运行:

小结: 第一种现象很好理解,当放置两个宽度为0dip或是wrap_content的按钮时,由于宽度并未确定,那Button1所占的宽度就是 1 / (1+2) = 1/ 3, 也就是总长度的1/3;Button2 所占的宽度是 2 / (1+2) = 2 / 3, 也就是总长度的2/3。

第二种现象就很奇怪了,其实这是因为View在绘制的时候有一个规则,如果给View添加了android:weight属性,那么这个View的最终宽度 = View本来定义的宽度 +   View在LinearLayout中剩余空间中所占比例的宽度。什么意思呢,假设线性布局的总宽度为 L ,

拿第一种现象来说

Button1的宽度 = 0dip + ( L - Button1的宽度(也就是0dip) - Button2的宽度(也是0dip) ) * 1/3 = 0dip + L * 1/3 = 1/3 L。
Button2的宽度 =  0dip + ( L - Button1的宽度(也就是0dip) - Button2的宽度(也是0dip) ) * 2/3 = 0dip + L * 2/3 = 2/3 L。

拿第二种现象来说

Button1的宽度 = L + ( L - Button1的宽度(也就是L) - Button2的宽度(也是L) ) * 1/3 = L + (-L) * 1/3 = L - 1/3 L = 2/ 3L。
Button2的宽度 = L + ( L - Button1的宽度(也就是L) - Button2的宽度(也是L) ) * 2/3 = L + (-L) * 2/3 = L - 2/3 L = 1/ 3L。

最新文章

  1. Nginx - Linux下按天分割日志
  2. 2016huasacm暑假集训训练五 J - Max Sum
  3. 在设置app icon时的问题
  4. C++之路进阶codevs1269(匈牙利游戏)
  5. ARM体系结构
  6. javascript 正则表达式基础知识汇总
  7. 分布式算法一——一致性hash算法
  8. Android应用市场提交入口
  9. Python Web 性能和压力测试 multi-mechanize
  10. calltree看代码调用图
  11. 1st_homework_SE--四则运算题目生成器
  12. sqlserver2012安装过程
  13. java+jsp+sql server实现网页版四则运算.
  14. 【算法】祭奠spfa 最短路算法dijspfa
  15. mysql免解压版安装教程步骤
  16. nodejs服务端使用jquery操作Dom
  17. VSCode 配置
  18. ansible学习笔记一
  19. MT【58】反演圆和极线极点和谐统一
  20. sping IOC和DI 初始化和关系

热门文章

  1. MySQL修炼之路三
  2. myEclipse项目部署点击Finish按钮没反应
  3. minikube国内在线部署体验
  4. Java-最常用的Java日志框架整理
  5. curl请求https资源的时候出现400
  6. css3卡片阴影效果
  7. JVM垃圾回收算法分析与演示【纯理论】
  8. MyBatis框架之注解开发
  9. Python 简单批量请求接口实例
  10. 应用安全测试技术DAST、SAST、IAST对比分析【转】