关于weight属性使用的一些细节
2015-08-29 18:17
423 查看
之前被这个属性困扰过好久,今天一个偶然的机会,终于把这个搞清楚了,现在与大家分享一下。
假设我们要在一个LinearLayout布局中显示两个按钮,button1和button2,button2的宽度是button1的二倍,正常情况下使用weight应该是这样的:
注意两个button的宽都是0dp
效果图:
可是如果换一种方式:
两个button的宽度都是
我以前就在这里不知道纠结了多少回,那么我们到底该怎么理解weight这个属性呢?
设置了weight属性的View的宽度等于原有宽度加上剩余空间的占比,其中剩余空间是指屏幕宽度相对于控件总宽度剩余的空间大小。
以第一种情况为例
假设屏幕宽度为L,第一个button原有宽度是0dp,那么该button的宽度为
其中(L-0)中,L表示屏幕宽度,0表示两个控件的总宽度
以第二种情况为例
假设屏幕宽度为L,因为两个都是match_parent,所以总宽度是2L,那么对于第一个button而言,它的宽度为:
其中(L-2L)中,L表示屏幕宽度,2L表示两个控件的总宽度
总结:建议大家在使用weight属性的过程中把相应的宽或者高设置为0dp,这也是Google推荐的做法。水平排列的话宽设置为0dp,竖直排列的话高设置为0dp.
假设我们要在一个LinearLayout布局中显示两个按钮,button1和button2,button2的宽度是button1的二倍,正常情况下使用weight应该是这样的:
<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" android:orientation="horizontal" > <Button android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="button1" /> <Button android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="2" android:text="button2" /> </LinearLayout>
注意两个button的宽都是0dp
效果图:
可是如果换一种方式:
<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" android:orientation="horizontal" > <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:text="button1" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="2" android:text="button2" /> </LinearLayout>
两个button的宽度都是
match_parent,情况立马发生转变:
我以前就在这里不知道纠结了多少回,那么我们到底该怎么理解weight这个属性呢?
设置了weight属性的View的宽度等于原有宽度加上剩余空间的占比,其中剩余空间是指屏幕宽度相对于控件总宽度剩余的空间大小。
以第一种情况为例
假设屏幕宽度为L,第一个button原有宽度是0dp,那么该button的宽度为
0+(L-0)×1/3 = (1/3)L;
其中(L-0)中,L表示屏幕宽度,0表示两个控件的总宽度
以第二种情况为例
假设屏幕宽度为L,因为两个都是match_parent,所以总宽度是2L,那么对于第一个button而言,它的宽度为:
L+(L-2L)×1/3 = (2/3)L
其中(L-2L)中,L表示屏幕宽度,2L表示两个控件的总宽度
总结:建议大家在使用weight属性的过程中把相应的宽或者高设置为0dp,这也是Google推荐的做法。水平排列的话宽设置为0dp,竖直排列的话高设置为0dp.
相关文章推荐
- POJ 2449 Remmarguts' Date (A*搜索求K短路)
- Oracle 笔记之视图
- Handler 机制学习之相关类
- 如何选择开发板和保护开发板
- linux alias设置别名永久生效
- jquery 中 live事件委派 与 bind事件绑定
- POJ 2449 Remmarguts' Date (A*搜索求K短路)
- Mysql 总结
- Oracle 笔记之子查询
- nginx缓存优先级
- python2.7 beautifulsoup学习使用
- JAVA基础学习(一)--JAVA入门和JDK的安装与配置
- 山东省第六届ACM省赛 H---Square Number 【思考】
- express源码阅读
- [C#] 等待启动的进程执行完毕
- Oracle 笔记之高级查询
- python2.7 beautifulsoup安装下载
- UVA 10801 Lift Hopping (最短路)
- Linux CentOS 6.5 用户 常用命令
- C链表操作