android 布局weight,036-布局-线性布局-layout_weight属性

接下来我们学习下LinearLayout中的另一个重要属性——android:layout_weight 。

这个属性允许我们使用比例的方式来指定控件的大小,它在手机屏幕的适配性方面可以起到非常重要

的作用。

比如我们正在编写一个消息发送界面,需要一个文本编辑框和一个发送按钮

android:orientation="horizontal"

android:layout_width="match_parent"

android:layout_height="match_parent">

android:id="@+id/input_message"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_weight="1"

android:hint="Type something"

/>

android:id="@+id/send"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_weight="1"

android:text="Send"

/>

这里竟然将EditText和Button的宽度都指定成了0dp,这样文本编辑框和按钮还能显示

出来吗?不用担心,由于我们使用了android:layout_weight 属性,此时控件的宽度就不

应该再由android:layout_width 来决定,这里指定成0dp是一种比较规范的写法。另外,dp

是Android中用于指定控件大小、间距等属性的单位,后面我们还会经常用到它。

然后在EditText和Button里都将android:layout_weight 属性的值指定为1,这表示EditText

和Button将在水平方向平分宽度。

我们还可以通过指定部分控件的layout_weight 值来实现更好的效果

android:orientation="horizontal"

android:layout_width="match_parent"

android:layout_height="match_parent">

android:id="@+id/input_message"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_weight="1"

android:hint="Type something"

/>

android:id="@+id/send"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Send"

/>

这里我们仅指定了EditText的android:layout_weight 属性,并将Button的宽度改回

wrap_content 。这表示Button的宽度仍然按照wrap_content 来计算,而EditText则会占满

屏幕所有的剩余空间。

ba3a0ef018c4a6335ed5f5630bb71d17.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值