android: android 布局中的weight 属性
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。
如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮,您的“推荐”将是我最大的写作动力!欢迎各位转载,但是未经作者本人同意,转载文章之后必须在文章页面明显位置给出作者和原文连接,否则保留追究法律责任的权利。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
2017-11-08 2.文件系统
2016-11-08 新浪微博客户端(22)-创建微博Cell