Android中LinearLayout布局

1、 首先声明只有在Linearlayout布局中,layout_weight属性才有效。

2、它是用来指定(剩余空闲空间)的分割比例,而非按比例分配整个空间。为什么这样说呢?看如下代码:


<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    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:text="按钮1"        android:layout_weight="2"/>     <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="按钮2"        android:layout_weight="1"/>     <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="按钮3"        android:layout_weight="1"/></LinearLayout>

可以看到三个按钮的android:layout_weight分别是2:1:1,那它们的宽度应该也是2:1:1,但按钮1却根本没有显示出来,所以android:layout_weight是按比例划分activity的宽度这一理解是错误的,正确的理解是android:layout_weight是按比例划分activity的剩余空间的。打个比方,activity的宽度是1080,因为三个按钮的android:layout_width都是等于"match_parent",所以三个按钮的宽度都是1080,而activity的宽度只有1080,所以activity的剩余空间为1080-1080-1080-1080=-2160,三个按钮按比例划分剩余空间,所以按钮1的宽度为1080+(-21602/4)=0,按钮2和按钮3的宽度都是1080+(-21601/2)=540,所以效果图是按钮2和按钮3宽度一样,各占activity宽度的一半。

3、另外android:layout_weight会引起争议,是因为在设置该属性的同时,设置android:layout_width为wrap_content和match_parent会造成两种截然相反的效果。

4、如果想用layout_weight平均分配空间,正确方式是将layout_width(或layout_height)设置为0dp,再通过layout_weight按比例分配空间即可。

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="horizontal">     <Button        android:layout_width="0dp"        android:layout_height="wrap_content"        android:text="按钮1"        android:layout_weight="2"/>     <Button        android:layout_width="0dp"        android:layout_height="wrap_content"        android:text="按钮2"        android:layout_weight="1"/>     <Button        android:layout_width="0dp"        android:layout_height="wrap_content"        android:text="按钮3"        android:layout_weight="1"/></LinearLayout>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值