关于android:layout_weight属性你不知道的事
来源:互联网 发布:linux vim 不保存退出 编辑:程序博客网 时间:2024/05/21 10:58
刚开始做安卓开发时,使用xml写布局时就使用过android:layout_weight属性吧。
首先该属性一定要是在Linearlayout布局中才会有效果。
这属性就是权重的意思:该 View的宽度或者高度等于原有宽度或者高度(android:layout_width)加上剩余空间的占比!(这里千万注意剩余空间)
直接上代码:
<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" tools:context="com.dgg1.weight.MainActivity"> <Button android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:background="#ff00ff" android:text="按钮1" /> <Button android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="2" android:background="#ffff00" android:text="按钮2" /></LinearLayout>
实现的效果:
这也是官方的写法。
下面我换一种写法:
<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" tools:context="com.dgg1.weight.MainActivity"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:background="#ff00ff" android:text="按钮1" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="2" android:background="#ffff00" android:text="按钮2" /></LinearLayout>
诶,这不是一模一样么(嘿嘿,不仔细看的人可能还真的觉得没改哪里)我这里把layout_width从0改成了match_parent。
实现的效果:
你会发现效果和之前的效果恰恰相反,为什么会出现这个效果呢?layout_weight属性的意思为控件原本的宽度+剩余空间的比例宽度!
第一种情况:假设这个屏幕的宽度为100,当你把宽度设置为0dp时,那button2的宽度就为0(控件的宽度)+100(剩余的宽度)*2/3 (比例)= 67(实际宽度),button1的宽度就为0+100*1/3 = 33;
第二种情况:假设这个屏幕的宽度为100,当你把宽度设置为match_parent时,那button1的宽度就为100,button2的宽度也为100,那么剩余宽度为100-(100+100)=-100(剩余宽度就为-100了),那么继续换算button1的实际宽度为100+(-100)*1/3 = 67,button2的实际宽度为100+(-100)*2/3 = 33了。
所以就会出现恰恰相反的结果了。(官方推荐使用第一种写法)
但是有时候使用到 include标签的复用布局时可能需要使用到第二种写法。
(如有问题或遗漏欢迎留言探讨,共同进步)
- 关于android:layout_weight属性你不知道的事
- Android中你也许不知道的线性布局Layout_weight属性权重比例分配原理
- android:layout_weight总有你不知道的用法.
- android:layout_weight总有你不知道的用法
- 你所不知道的layout_weight
- 你可能不知道的layout_weight
- 关于eLTE,你不知道的事
- 关于Activity你不知道的事
- 关于越界你不知道的事~~
- 关于浏览器你不知道的事
- 关于警笛你不知道的事
- android中TextVIew中你不知道的属性
- 关于 Android N 那些你不知道的事儿
- 一些你不知道的CSS属性
- android:layout_weight属性你真的理解吗
- 关于Android的layout_weight
- 关于layout_weight属性的使用
- 关于《越狱》,你不知道的5件事
- Unity使用Share-SDK接微信登录和分享的总结(Android)
- 教你如何写一个JAVA注解
- SDN 开源解决方案中,OVN增长率最快
- 自己真的能搭建一个云盘!只要半个小时!全平台支持!
- HOOK技术(钩子)
- 关于android:layout_weight属性你不知道的事
- ZooKeeper
- jedis使用
- csdn中如何转载别人的文章?
- Interesting Calculator CSU
- 简单且广泛运用的模式——单例模式
- 2017.08.21
- JavaScript基础库
- Linux进程内存分析和内存泄漏定位