Android中 android:layout_weight 属性

本文详细介绍了Android布局中android:layout_weight属性的作用与用法。该属性用于设置线性布局中不同视图元素的重要度,从而调整它们在屏幕上的相对大小。通过具体的代码示例展示了如何利用这一属性来实现灵活的界面布局。

 Android布局中 android:layout_weight 属性解释

定义:所有View(视图)元素中都有一个XML属性android:layout_weight,其值为0,1,2,3...等整数值。
            使用了之后,其对应界面中的元素比例就会发生变化,变大或者变小。layout_weight属性其实就是一个元素重要度的属性,用于在线性布局中为不同的view元素设置不同的重要度。




 




<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android
     android:orientation="vertical" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent"  > 

 <TextView    android:id="@+id/a1" 
     android:layout_width="fill_parent"  
     android:layout_height="wrap_content"  
     android:text="" 
     android:layout_weight="1"  /> 
 <TextView    android:id="@+id/a2" 
     android:layout_width="fill_parent"  
     android:layout_height="wrap_content"  
     android:text="" 
     android:layout_weight="2"  /> 

 </LinearLayout> 

 欢迎各位朋友,一起来讨论Android方面的技术难点。

 android:layout_weight属性主要用来设置控件在屏幕上的位置空间,代码中如果第一个TextView中为1,第二个TextView为2,则这两个控件一个占总空间的1/3,

 另一个占总空间的2/3。


 在一个LinearLayout内各个组件是按weight值以正比形式显示在屏幕上 ,而在LinearLayout之间以反比的形式显示在屏幕上  ,很奇怪吧。




 官方文档关于这个属性的解释

 LinearLayout  also supports assigning aweight to individual children. This attribute assigns an"importance" value to a view, and allows it to expand to fill anyremaining   space in the parent view. Child views can specify aninteger weight value, and then any remaining space in the viewgroup is assigned to children in the proportion of their    declaredweight. Default weight is zero. For example, if there are threetext boxes and two of them declare a weight of 1, while the otheris given no weight (0), the third text   box without weight will notgrow and will only occupy the area required by its content. Theother two will expand equally to fill the space remaining after allthree boxes are measured. If the third box is then given a weightof 2 (instead of 0), then it is now declared "more important" thanboth the others, so it gets half the total remaining space, whilethe first two share the rest equally.


 其实很简单,weight本来的意思就是重量,即 这个属性所代表的是重要程度,而不是比例

 解释:
 如果三个view水平排列,前两个view的wieght是1,第三个是默认值0,( 所有的视图都有一个layout_weight值,其默认值为0,)表示视图多大就占据多大的屏幕空间。可见第三个view的weight最低,那么第三个view就只会占用自己内容所需的宽度,剩下的宽度会被前两   个view平分。

 如果第三个view的wieght是2,那么前两个view就会平分剩余的宽度,而第三个会(gets half  the total) 占据所有空间的一半。

 至于Linearlayout的weight属性越小的所占空间越多,我觉得这是因为Linearlayout的默认高度问题,一个简单的实验当我把两个Linearlayout的值设为1和5的时候,屏幕比例  依然不变,因为第一个Linearlayout的默认大小就是那么大


很乱,这个东西,不好解释。
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值