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