关于weight属性使用的一些细节
之前被这个属性困扰过好久,今天一个偶然的机会,终于把这个搞清楚了,现在与大家分享一下。
假设我们要在一个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.
版权声明:本文为博主原创文章,未经博主允许不得转载。若有错误地方,还望批评指正,不胜感激。
蓝天为路,阳光满屋。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?