Android布局基础知识之wrap_content与match_parent的区别,(和配合使用layout_weight的不同)

Android布局基础知识之wrap_content与match_parent的区别,(和配合使用layout_weight的不同)

一、定义

match_parent:表示让当前控件的大小和父布局的大小一样,即由父布局来决定当前控件的大小。

wrap_content:表示让当前控件的大小刚好能够包含里面的内容,即由控件内容决定当前控件的大小。

二、配合layout_weight的不同

layout_weight:表示线性分割原本应有长度的权重,要和wrap_content和match_parent配合使用。

layout_weight的计算方式:LinearLayout布局中含有weight的子控件时,LinearLayout会measure两次

设屏幕宽度为X,子控件1为x1,子控件2为x2

第一次测量宽度:x1=X, x2=X ,total_width为2X;
(因为用了weight,所以linearLayout每次measure child时不考虑前一个已经占用的大小)

第二次计算delta(偏差):delta=X-total_width=-X, 然后会将x1的宽度设为 X+delta1/3=0.66X, x2的宽度为 X+delta*2/3=0.33X。

试着理解这句话!!
1、layout_width="match_parent"时,
控件的宽度为整个父布局宽度,即match_parent
剩余空间宽度 = 父布局宽度 - 总权重*控件宽度(这里为父布局宽度)
分析:结果为负值,因此比例为反比。

layout_width="wrap_content"时
控件的宽度为内容宽度,而wrap_content表示为0dp
剩余空间宽度 = 父布局宽度 - 总权重*控件宽度(这里为0dp)
分析:结果为正值,因此比例为正比。

通用计算长度公式:长度=控件长度+权重比例*剩余空间大小

Google官方推荐,当使用weight属性时,将width设为0dp即可,效果跟设成wrap_content是一样的。这样weight就可以理解为占比了!

  • 13
    点赞
  • 87
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,你可以在布局文件中添加两个 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> ``` 这样就在布局文件中添加了两个按钮:取消和确认。你可以根据需要修改按钮的文本和样式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值