Android布局基础知识:wrap_content,match_parent,layout_weight

wrap_content:是layout_width和layout_height的属性值之一,表示和自身内容一样的长度。

match_parent:是layout_width和layout_height的属性值之一,表示和父组件一样的长度。

layout_weight:是布局文件的一个属性,它的值表示线性分割原本应有长度的权重,要和wrap_content和match_parent配合使用,不同情况列举如下:

和wrap_content配合:先按照内容的多少去设定空间大小,然后按照权重的比例分配剩余控件。即当控件没有内容或内容未超出按照权重比例分配的空间时,就按照layout_weight设定的权重比例分配空间,当内容大小超过这样分配的空间时,控件就会扩张,其实就是按照wrap_content来占用空间了,剩下的空间仍然按照本段定理来分配。

和match_parent配合:空间计算公式:空间大小=父容器大小+权重比例*剩余空间大小,比如两个同级控件A,B都是match_parent,A的layout_weight为1,B的layout_weight为2(总空间为1match_parent,所需空间为2match_parent,剩余空间为两者之差),空间A=1match_parent+1/(1+2)*(1match_parent-2match_parent)=2/3match_parent,同理,空间B=1/3match_parent。这个现象和正常情况有些相反,但是可以有效保证空间分配到的比例固定,不会被内容撑大。

和0dp配合:将layout_weight或者layout_height设为0dp,将直接按照layout_weight权重的比例分配空间,且不会被内容撑大。

  • 60
    点赞
  • 172
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
好的,你可以在布局文件中添加两个 Button 控件,如下所示: ``` <?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="vertical"> <EditText android:id="@+id/ipEditText" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入服务器IP地址" /> <EditText android:id="@+id/portEditText" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入服务器端口号" /> <Button android:id="@+id/connectButton" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="连接" /> <SeekBar android:id="@+id/seekBar_x" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:max="30" android:progress="0" /> <ScrollView android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"> <SeekBar android:id="@+id/seekBar_y" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="32dp" android:max="30" android:progress="0" /> </ScrollView> <Button android:id="@+id/sendMessageButton" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="发送消息" /> <Button android:id="@+id/cancelButton" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="取消" /> <Button android:id="@+id/confirmButton" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="确认" /> </LinearLayout> ``` 这样就在布局文件中添加了两个按钮:取消和确认。你可以根据需要修改按钮的文本和样式。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值