LinearLayout的两个关键属性(layout_gravity&weight)

本文详细介绍了Android中布局属性layout_gravity和layout_weight的用法。layout_gravity用于设置控件在布局中的对齐方式,而layout_weight则通过比例分配的方式确定控件大小。文章通过实例展示了如何实现控件的合理布局。

1、android:layout_gravity

      指定控件在布局中的对齐方式。当排列方向是vertical时,只有水平方向上的对齐方式才会生效;horizontal则相反。

       (android:gravity指定文字在控件中的对齐方式)

2、android:layout_weight

      使用比例的方式来指定控件大小。

      e.g.:水平排列的一个EditView和Button

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<EditText
android:id="@+id/input_message"
android:layout_width="0dp"                  //规范写法,此时控件的宽度就仅由weight来决定
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="Type something"
/>
<Button
android:id="@+id/send"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"                        //EditView和Button以1:1的比例水平排列
android:text="Send"
/>
</LinearLayout>

如果仅指定EditView的weight属性,将Button的width改为wrap_content,Button的宽度仍按wrap_content计算,而Editview会占据剩下的空间,这种方式编写的程序,不仅在各种屏幕上适配性很好,而且看起来也很舒服,如下图。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值